在JSON.NET中解析JSON数组
我在REST API响应中有JSON对象:
{ Result: [ { "id": 1, "id_endpoint": 1, "name": "Endpoint 1", "description": "Endpoint 1", "unit": "mmol", "minthreshold": 30, "maxthreshold": -15, "id_device": 4, "value": 7, "time": "2016-12-24T21:20:19.000Z", "address": "Endpoint 1", "id_user": 1 }, { "id": 2, "id_endpoint": 1, "name": "Endpoint 1", "description": "Endpoint 1", "unit": "mmol", "minthreshold": 30, "maxthreshold": -15, "id_device": 4, "value": 6, "time": "2016-12-24T21:20:16.000Z", "address": "Endpoint 1", "id_user": 1 }, { "id": 3, "id_endpoint": 1, "name": "Endpoint 1", "description": "Endpoint 1", "unit": "mmol", "minthreshold": 30, "maxthreshold": -15, "id_device": 4, "value": 8, "time": "2016-12-24T21:18:38.000Z", "address": "Endpoint 1", "id_user": 1 } ], StatusCode: 200 }
如果错误,他们会得到:
{ Result: null, StatusCode: 404 }
我正在使用JSON.NET,而且我使用的是DeviceInfo.cs类
public class DeviceInfo { public int DeviceID {get;set;} public int EndpointID {get;set;} public string DeviceName {get;set;} public double MinThreshold {get;set;} public double MaxThreshold {get;set;} public double CurrentValue {get;set;} public DateTime ValueTime {get;set;} public string EndpointAddress {get;set;} public int IDUser {get;set;} }
我的问题是如何在JSON对象中解析Result数组并将其存储在DeviceInfo类中?
您需要属性帮助Newtonsoft.Json将源映射到您的类。
public class DeviceInfo { [JsonProperty("id")] public int DeviceID { get; set; } [JsonProperty("id_endpoint")] public int EndpointID { get; set; } [JsonProperty("name")] public string DeviceName { get; set; } [JsonProperty("minthreshold")] public double MinThreshold { get; set; } [JsonProperty("maxthreshold")] public double MaxThreshold { get; set; } [JsonProperty("value")] public double CurrentValue { get; set; } [JsonProperty("time")] public DateTime ValueTime { get; set; } [JsonProperty("address")] public string EndpointAddress { get; set; } [JsonProperty("id_user")] public int IDUser { get; set; } }
还有你的json被包裹的外层。
public class RootObject { public List Result { get; set; } public int StatusCode { get; set; } }
最后,您可以使用JsonConvert反序列化您的json。
var result = JsonConvert.DeserializeObject(json);
您可以使用JsonDeserialize来解析json
var array = JsonConvert.DeserializeObject>(str);
请参考以下代码:
var response = JsonConvert.DeserializeObject>(JSONstring); if(response != null && response["StatusCode"] == "200") { List lstResult = JsonConvert.DeserializeObject(response["Result"]); }
我希望这会有所帮助。
上述就是C#学习教程:在JSON.NET中解析JSON数组分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1024890.html