Parse JSON array in JSON.NET

前端 未结 3 821
梦如初夏
梦如初夏 2021-01-24 03:51

I have JSON object in REST API response:

{
    Result:
    [
        {
            \"id\": 1,
            \"id_endpoint\": 1,
            \"name\": \"Endpoint 1\         


        
相关标签:
3条回答
  • 2021-01-24 03:55

    You need attributes help Newtonsoft.Json mapping the source to your class.

    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; }
    }
    

    And an outer class which your json was wrapped.

    public class RootObject
    {
        public List<DeviceInfo> Result { get; set; }
        public int StatusCode { get; set; }
    }
    

    Finally, you can use JsonConvert to Deserialize your json.

    var result = JsonConvert.DeserializeObject<RootObject>(json);
    
    0 讨论(0)
  • 2021-01-24 04:18

    You can use JsonDeserialize to parse json

    var array = JsonConvert.DeserializeObject<List<DeviceInfo>>(str);
    
    0 讨论(0)
  • 2021-01-24 04:18

    Please refer to following code:

    var response =  JsonConvert.DeserializeObject<Dictionary<string,object>>(JSONstring);
    
    if(response != null && response["StatusCode"] == "200")
    {
         List<DeviceInfo> lstResult = JsonConvert.DeserializeObject<List<DeviceInfo>(response["Result"]);
    }
    

    I hope this would help.

    0 讨论(0)
提交回复
热议问题