How to Deserialize a Json Array with C#?

余生长醉 提交于 2019-12-27 06:14:04

问题


I use RestSharp to make a Rest API Call.

public class GetValues
{
    public string Values{ get; set; }
}

public class JsonObjects
{
    public List<GetValues> Values{ get; set; }
}

RestRequest restRequest = new RestRequest("api/tempCatalog/temp1", Method.GET);

restRequest.AddHeader("Accept", "application/json");
restRequest.AddHeader("Content-Type", "application/json");
restRequest.AddHeader("Authorization", token);

IRestResponse restResponse = clientRest.Execute(restRequest );
string Content = restResponse.Content;

JsonObjects.Values= JsonConvert.DeserializeObject<JsonObjects>(Content).Values;

I have the above code and it works.

But when the JSON Rest Response contains an array it throws an Exception when deserializing.

When the Rest Response is like this , sometimes ,

{ "Fields": [ "Value.temp", ] } 

I get this exception:

Newtonsoft.Json.JsonSerializationException: 'Error converting value'

ArgumentException: Could not cast or convert from System.String to Namespace.GetValues.

When I say sometimes i mean that i use this Deserialize in multiple API calls this in the question was just an example

These are some Json Arrays that I have as Rest response and I want to deserialize them.

{
  "Fields": [

    "Temp1.Value",
    "Temp2.Value",
    "Temp3.Value",
    "Temp4.Value"
  ]

}

or these??

{

  "Errors":
 [

{

      "ErrorCode": "Temp Number",
      "Message": "Temp Message",
      "TempName": "Name"
    }

  ],


  "ValueErrors": []

}

or these??

{

"Total": 1,

"Categories": [

{

      "Id": "tempID",
      "Name": "tempName"
    }

  ]

}

回答1:


If I'm reading it correctly, you are getting the following JSON string:

{ 
    "Fields": [ 
        "Value.temp", 
    ] 
}

The class you're deserializing to must match this structure, and yours, unfortunately, don't.

So JsonObjects must look like this:

public class JsonObjects
{
    public List<string> Fields { get; set; }
}


来源:https://stackoverflow.com/questions/59411274/how-to-deserialize-a-json-array-with-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!