Newtonsoft.Json高级篇:TypeNameHandling设置
发布时间:2020-12-16 18:42:07 所属栏目:百科 来源:网络整理
导读:此示例使用 TypeNameHandling ?设置在序列化JSON和读取类型信息时包含类型信息,以便在反序列化JSON时创建创建类型 Sample public abstract class Business{ public string Name { get ; set ; }} public class Hotel : Business{ public int Stars { get ;
此示例使用TypeNameHandling?设置在序列化JSON和读取类型信息时包含类型信息,以便在反序列化JSON时创建创建类型 Sample public abstract class Business { public string Name { get; set; } } public class Hotel : Business { public int Stars { get; set; } } public class Stockholder { public string FullName { get; set; } public IList<Business> Businesses { get; set; } } 使用 Stockholder stockholder = new Stockholder { FullName = "Steve Stockholder",Businesses = new List<Business> { new Hotel { Name = "Hudson Hotel",Stars = 4 } } }; string jsonTypeNameAll = JsonConvert.SerializeObject(stockholder,Formatting.Indented,new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }); Console.WriteLine(jsonTypeNameAll); // { // "$type": "Newtonsoft.Json.Samples.Stockholder,Newtonsoft.Json.Tests",// "FullName": "Steve Stockholder",// "Businesses": { // "$type": "System.Collections.Generic.List`1[[Newtonsoft.Json.Samples.Business,Newtonsoft.Json.Tests]],mscorlib",// "$values": [ // { // "$type": "Newtonsoft.Json.Samples.Hotel,// "Stars": 4,// "Name": "Hudson Hotel" // } // ] // } // } string jsonTypeNameAuto = JsonConvert.SerializeObject(stockholder,new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); Console.WriteLine(jsonTypeNameAuto); // { // "FullName": "Steve Stockholder",// "Businesses": [ // { // "$type": "Newtonsoft.Json.Samples.Hotel,// "Stars": 4,// "Name": "Hudson Hotel" // } // ] // } // for security TypeNameHandling is required when deserializing Stockholder newStockholder = JsonConvert.DeserializeObject<Stockholder>(jsonTypeNameAuto,new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto }); Console.WriteLine(newStockholder.Businesses[0].GetType().Name); // Hotel 具体内容详见官方文档:https://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm 解决的具体问题:可以支持复杂的继承结构: string jsonTypeNameAll = JsonConvert.SerializeObject(xx,new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All,ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); var oo= JsonConvert.DeserializeObject<StartConfig>(File.ReadAllText(path),ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); ISupportInitialize iSupportInitialize = (ISupportInitialize) oo; iSupportInitialize?.EndInit(); var o9=oo.GetComponent<InnerConfig>();//实例化StartConfig对象的子对象 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 如何将存储过程添加到Windows Installer中
- ruby – 如何自定义will_paginate链接库?
- ruby-on-rails – rails_admin与rails-api冲突
- c# – System.Drawing.Graphics.DrawString – “参数无效”
- vb.net小试三层架构
- c# – 当gridview具有autogeneratecolumns = true时,如何更
- UFS (Universal Flash Storage)入门
- Swift3 GCD的基本用法(二) - 队列的循环/挂起/恢复、其他
- 在Xcode中复制捆绑资源时,解析符号链接
- flash – 使用computeSpectrum()进行音高检测返回FFT值