栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Json.Net对具有附加属性的自定义集合进行序列化/反序列化

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Json.Net对具有附加属性的自定义集合进行序列化/反序列化

问题如下:当对象实现时

IEnumerable
,JSON.net将其标识为值数组,并按照数组Json语法(不包括属性)对其进行序列化,例如:

 [ {"FooProperty" : 123}, {"FooProperty" : 456}, {"FooProperty" : 789}]

如果要序列化它保留属性,则需要通过定义一个custom来手工处理该对象的序列化

JsonConverter

// intermediate class that can be serialized by JSON.net// and contains the same data as FooCollectionclass FooCollectionSurrogate{    // the collection of foo elements    public List<Foo> Collection { get; set; }    // the properties of FooCollection to serialize    public string Bar { get; set; }}public class FooCollectionConverter : JsonConverter{    public override bool CanConvert(Type objectType)    {        return objectType == typeof(FooCollection);    }    public override object ReadJson(        JsonReader reader, Type objectType,         object existingValue, JsonSerializer serializer)    {        // N.B. null handling is missing        var surrogate = serializer.Deserialize<FooCollectionSurrogate>(reader);        var fooElements = surrogate.Collection;        var fooColl = new FooCollection { Bar = surrogate.Bar };        foreach (var el in fooElements) fooColl.Add(el);        return fooColl;    }    public override void WriteJson(JsonWriter writer, object value,   JsonSerializer serializer)    {        // N.B. null handling is missing        var fooColl = (FooCollection)value;        // create the surrogate and serialize it instead         // of the collection itself        var surrogate = new FooCollectionSurrogate()         {  Collection = fooColl.ToList(),  Bar = fooColl.Bar         };        serializer.Serialize(writer, surrogate);    }}

然后按以下方式使用它:

var ss = JsonConvert.SerializeObject(collection, new FooCollectionConverter());var obj = JsonConvert.DeserializeObject<FooCollection>(ss, new FooCollectionConverter());


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/465557.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号