问题描述
我有以下 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 反序列化特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!