将json的动态属性读入.net C#
我在点击API后得到了json格式:
{ "7407": { "survey_id": "406", "device_id": "1", "response_time": "2013-10-10 16:14:01", "timezone": "0", "language_id": "en", "response_id": "7407", "device_alias": "QR Code App", "site_name": "QR Code App", "country_name": "United States", "state_name": "New York", "city_name": "Suffern", "zip": "", "voucher_name": null, "voucher_mode": null, "surveyee_name": null, "surveyee_email": null, "surveyee_phone": null, "ques": { "": [] } }, "7408": { "survey_id": "406", "device_id": "1", "response_time": "2013-10-10 16:36:56", "timezone": "0", "language_id": "en", "response_id": "7408", "device_alias": "QR Code App", "site_name": "QR Code App", "country_name": "India", "state_name": "Gujarat", "city_name": "Ahmedabad", "zip": "", "voucher_name": null, "voucher_mode": null, "surveyee_name": null, "surveyee_email": null, "surveyee_phone": null, "ques": { "": [] } } }
我正在使用JSON.Net
来读取上面给出的json数据。
要将此数据映射到.Net代码,我将需要.net中的类,其名称与json字符串中的名称相同。 但是 json中有一些属性可以是动态的(在我的例子中是“7407”,“7408”等),即可以根据我们传入参数的内容来改变这个值。
我的问题是,我们如何将json属性(它们本质上是动态的,并且可以根据提供给apis的参数具有任何值)映射到我们的.net类?
您可以将其映射到字典。 动态属性是DictionaryIem的键,Objet是DictionaryItem的值。
对于Exmaple:
public class MyClass { public void readJson) { var json = "{"7407": {"survey_id": "406","device_id": "1",},"7408": {"survey_id": "406","device_id": "1",}}"; Dictionary dict = Newtonsoft.Json.JsonConvert.DeserializeObject>(json); var count = dict.Keys.Count; } } public class MyObject { public string survey_id { get; set; } public string device_id { get; set; } }
对于这个例子,我简化了你的json。 所以它看起来像这样:
{ "7407": { "survey_id": "406", "device_id": "1" }, "7408": { "survey_id": "406", "device_id": "1" } }
Js对象是一个字典,因此您可以使用key = some属性和值 – .Net代码映射到Dictionary
Dictionary
我能找到处理这种JSON数据的最好方法是使用JSON.Net库的JObject
类。 例如:
Newtonsoft.Json.Linq.JObject jSonObject = JsonConvert.DeserializeObject(somejsonstring);
然后你可以循环或应用一些其他逻辑来读取jSonObject
上述就是C#学习教程:将json的动态属性读入.net C#分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/949811.html