Csharp/C#教程:使用Json.net反序列化时处理额外的成员分享


使用Json.net反序列化时处理额外的成员

假设我想将一组Json数据反序列化为Person对象。

class Person { [DataMember] string name; [DataMember] int age; [DataMember] int height; object unused; } 

但是,如果我有如下所示的Json数据:

 { "name":"Chris", "age":100, "birthplace":"UK", "height":170, "birthdate":"08/08/1913", } 

“birthdate”和“birthplace”字段不属于Person类。 但是我仍然希望保留这些字段,那么是否可以使用Json.net或其他可以将这些额外字段存储到Person字段之一的库,例如上面声明的“unused”?

您应该可以使用[JsonExtensionData]属性: http ://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension- 数据

 void Main() { var str = "{rn "name":"Chris",rn "age":100,rn "birthplace":"UK",rn "height":170," + "rn "birthdate":"08/08/1913",rn}"; var person = JsonConvert.DeserializeObject(str); Console.WriteLine(person.name); Console.WriteLine(person.other["birthplace"]); } class Person { public string name; public int age; public int height; [JsonExtensionData] public IDictionary other; } 

是的,您可以使用JSON.NET :

上述就是C#学习教程:使用Json.net反序列化时处理额外的成员分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 dynamic dycperson= JsonConvert.DeserializeObject(@"{ 'name':'Chris', 'age':100, 'birthplace':'UK', 'height':170, 'birthdate':'08/08/1913'}"); Person person = new Person{ name = dycperson.name, age=dycperson.age, height=dycperson.height, unused= new {birthplace = dycperson.birthplace, birthdate=dycperson.birthdate} }; 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/961661.html

(0)
上一篇 2021年11月26日
下一篇 2021年11月26日

精彩推荐