Doubt when deserializing JSON C#objects

Asked

Viewed 1,037 times

3

I am deserializing the JSON below, and would like to know, if I need to create a class with all attributes related to this JSON, or can I just create with the attributes I need to use?

Am I going the right way? I would like opinions about consuming API’s as it is the first time I use the technology.

JSON

[
   {
      "name":"Brazil",
      "topLevelDomain":[
         ".br"
      ],
      "alpha2Code":"BR",
      "alpha3Code":"BRA",
      "callingCodes":[
         "55"
      ],
      "capital":"Brasília",
      "altSpellings":[
         "BR",
         "Brasil",
         "Federative Republic of Brazil",
         "República Federativa do Brasil"
      ],
      "region":"Americas",
      "subregion":"South America",
      "population":206135893,
      "latlng":[
         -10.0,
         -55.0
      ],
      "demonym":"Brazilian",
      "area":8515767.0,
      "gini":54.7,
      "timezones":[
         "UTC-05:00",
         "UTC-04:00",
         "UTC-03:00",
         "UTC-02:00"
      ],
      "borders":[
         "ARG",
         "BOL",
         "COL",
         "GUF",
         "GUY",
         "PRY",
         "PER",
         "SUR",
         "URY",
         "VEN"
      ],
      "nativeName":"Brasil",
      "numericCode":"076",
      "currencies":[
         {
            "code":"BRL",
            "name":"Brazilian real",
            "symbol":"R$"
         }
      ],
      "languages":[
         {
            "iso639_1":"pt",
            "iso639_2":"por",
            "name":"Portuguese",
            "nativeName":"Português"
         }
      ],
      "translations":{
         "de":"Brasilien",
         "es":"Brasil",
         "fr":"Brésil",
         "ja":"ブラジル",
         "it":"Brasile",
         "br":"Brasil",
         "pt":"Brasil",
         "nl":"Brazilië",
         "hr":"Brazil"
      },
      "flag":"https://restcountries.eu/data/bra.svg",
      "regionalBlocs":[
         {
            "acronym":"USAN",
            "name":"Union of South American Nations",
            "otherAcronyms":[
               "UNASUR",
               "UNASUL",
               "UZAN"
            ],
            "otherNames":[
               "Unión de Naciones Suramericanas",
               "União de Nações Sul-Americanas",
               "Unie van Zuid-Amerikaanse Naties",
               "South American Union"
            ]
         }
      ]
   }
]

Class with the attributes I need.

public class APIRestPaises
{
    public string NativeName { get; set; }
    public string Alpha3Code { get; set; }
}

Reading the API

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

    var result = JsonConvert.DeserializeObject<APIRestPaises>(jsonResponse);
}
  • You are consuming and are returning the data correctly?

  • @Virgilionovic, Yes , is returning the data correctly, I’m only having trouble deserealizing the JSON

  • I mean, you’re in trouble on that line JsonConvert.DeserializeObject<APIRestPaises>???

  • 1

    @Virgilionovic, I did exactly what our friend down there said, I’m getting the data right, but my problem is being when I perform JSON, I mean, I created my class with just the attributes I need, so he gives the following below, now my question is, as I do to perform only the attributes I need, I may be missing something.

  • 1

    ERROR: Additional information: Cannot 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<T> 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.

  • Nicolar and then it worked?

  • @Virgilionovic, I can only ask one last question ?

  • My question is this, let’s assume that I have a product registration and I’m always updating my product registration via a product API of some company, as I would this update of records, I mean, put in my register the updates or insertions of new products, I would have to go through all this and check the differences ? I stayed in this doubt of where to make this call of the API, because it is expensive to always keep calling this correct method ?

  • The coding is normal, the company will document this for you and with this documentation will be created the necessary code, to work with this API. So it depends on the company that will provide the code.

Show 4 more comments

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 his return json is a list of values then on the line DeserializeObject do so:

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

or even

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

or also 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, is what the json returned also represents, and therefore error:

ERROR: Additional information: Cannot 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.

References:

  • 1

    Solved @Virgilio, thanks again friend. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.