简体   繁体   中英

How to Deserialize a Json Array with C#?

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

  ]

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM