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 反序列化特定属性
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
