Doubt when deserializing objects JSON C #

3

asked by anonymous 28.09.2017 / 03:49

1 answer

3

The correct code is as follows:

using (WebClient client = new WebClient())
{
    client.Encoding = Encoding.UTF8;

    var jsonResponse = client.DownloadString(@"https://restcountries.eu/rest/v2/all");

    var result = JsonConvert.DeserializeObject<List<APIRestPaises>>(jsonResponse);
}

Because your return json is a list of values then in line DeserializeObject do so:

var result = JsonConvert.DeserializeObject<List<APIRestPaises>>(jsonResponse);

or

var result = JsonConvert.DeserializeObject<APIRestPaises[]>(jsonResponse);

Or create a class like this:

public class Rootobject: List<APIRestPaises>
{
}

and in the code:

var result = JsonConvert.DeserializeObject<Rootobject>(jsonResponse);

This will represent a list of values, that is what the json returned also represents, and therefore of the error:

  

ERROR: Additional information: Can not deserialize the current JSON   array (e.g. [1,2,3]) into type 'Project.ERP.Desktop.APIRestPaises'   because the type requires a JSON object (e.g. {"name": "value"}) to   deserialize correctly. To fix this error either change the JSON to a   JSON object (e.g. {"name": "value"}) or change the deserialized type to   an array or a type that implements a collection interface (e.g.   ICollection, IList) like List that can be deserialized from a JSON    array . JsonArrayAttribute can also be added to the type to force it to   deserialize from a JSON array .

28.09.2017 / 15:22