JSON.NET反序列化特定属性

编程入门 行业动态 更新时间:2024-10-28 00:21:45
本文介绍了JSON.NET反序列化特定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有如下的 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反序列化特定属性

本文发布于:2023-11-14 21:32:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588551.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   序列化   JSON   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!