JSON.NET反序列化特定属性 [英] JSON.NET deserialize a specific property
问题描述
我有如下的 JSON
文本:
{
PropOne:{
文:数据
}
PropTwo:数据2
}
我要反序列化 PropOne
成键入 PropOneClass
无反序列化对象的任何其他属性的开销。可通过使用JSON.NET做?
公共牛逼GetFirstInstance< T>(字符串propertyName的,串JSON)
{
使用(VAR stringReader =新StringReader(JSON))
使用(VAR jsonReader =新JsonTextReader(stringReader))
{
而(jsonReader.Read())
{
如果(jsonReader.TokenType == JsonToken.PropertyName
&功放;&安培; (字符串)jsonReader.Value == propertyName的)
{
jsonReader.Read(); VAR串行=新JsonSerializer();
返回serializer.Deserialize< T>(jsonReader);
}
}
返回默认(T);
}
}公共类的MyType
{
公共字符串文本{搞定;组; }
}公共无效测试()
{
JSON字符串={\\PropOne \\:{\\文本\\:\\DATA \\} \\PropTwo \\:\\数据2 \\}; MyType的=的myType&GetFirstInstance LT; MyType的>(PropOne,JSON); 的Debug.WriteLine(myType.Text); //数据
}
该方法避免了反序列化整个对象。但要注意的是,如果JSON是这样只会提高性能 显著的大,而你反序列化属性在数据比较早。否则,你应该只反序列化整个事情,拔出你想,像jcwrequests回答表演的部分。
I have the following JSON
text:
{
"PropOne": {
"Text": "Data"
}
"PropTwo": "Data2"
}
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"
}
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反序列化特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!