JSON.NET deserialize a specific property(JSON.NET 反序列化特定属性)
问题描述
我有以下 JSON
文本:
{
"PropOne": {
"Text": "Data"
}
"PropTwo": "Data2"
}
我想将 PropOne
反序列化为 PropOneClass
类型,而无需反序列化对象上的任何其他属性.这可以使用 JSON.NET 完成吗?
I want to deserialize PropOne
into type PropOneClass
without the overhead of deserializing any other properties on the object. Can this be done using JSON.NET?
推荐答案
public T GetFirstInstance<T>(string propertyName, string json)
{
using (var stringReader = new StringReader(json))
using (var jsonReader = new JsonTextReader(stringReader))
{
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName
&& (string)jsonReader.Value == propertyName)
{
jsonReader.Read();
var serializer = new JsonSerializer();
return serializer.Deserialize<T>(jsonReader);
}
}
return default(T);
}
}
public class MyType
{
public string Text { get; set; }
}
public void Test()
{
string json = "{ "PropOne": { "Text": "Data" }, "PropTwo": "Data2" }";
MyType myType = GetFirstInstance<MyType>("PropOne", json);
Debug.WriteLine(myType.Text); // "Data"
}
这种方法避免了必须反序列化整个对象.但请注意,只有当 json 显着很大并且您要反序列化的属性在数据中相对较早时,这才会提高性能.否则,你应该反序列化整个事情并取出你想要的部分,比如 jcwrequests 回答节目.
This approach avoids having to deserialize the entire object. But note that this will only improve performance if the json is significantly large, and the property you are deserializing is relatively early in the data. Otherwise, you should just deserialize the whole thing and pull out the parts you want, like jcwrequests answer shows.
这篇关于JSON.NET 反序列化特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JSON.NET 反序列化特定属性


基础教程推荐
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01