问题
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