Search code examples
c#asp.netjsonconverter

Converting json to c# object


I have an api that returns me a json with information about the data transition and an array with data

{
    "code": "200",
    "result": true,
    "message": "",
    "data": {
        "item": [
            {
                "id": "5",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
            {
                "id": "7",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
        ],
        "count": 2
    }
}

I have a class that is referring to the return of items

class Category
 {
     public int Id { get; set; }
     public string Descricao { get; set; }
     public int Status { get; set; }
     public string Observacao { get; set; }
 }

Main.cs

 var stringJson = await response.Content.ReadAsStringAsync();

my string stringJson gets the following value

"\r\n\r\n{\"code\":\"200\",\"result\":true,\"message\":\"\",\"data\":{\"item\":[{\"id\":\"5\",\"descricao\":\"TesteDesc\",\"observacao\":\"TesteObs\",\"status\":\"1\"}],\"count\":2}}"

but when I try to convert

var Data = JsonConvert.DeserializeObject<IEnumerable<Category>>(stringJson);

error is displayed

Erro: cannot deserialize the current json object (e.g. {"name":"value"}) into type ...

How can I create an array of objects with json data? taking only the date and item

is it possible for me to retrieve the values formally alone, for example I make a variable bool status = jsonConvert.get ("status"); something like that?


Solution

  • Follow structure! Your json contains more than just a List<Category>. When deserialzing, you will have to deserialzr to a class like the following

     class Wrapper {
          public string code {get;set;}
          public bool result {get;set;}
          public string message {get;set;}
          public Data data {get; set;}
      }
    
    
     class Data {
          public List<Category> item {get;set;}
          public int count {get; set;}
     }
    

    Then you can deserialize using

     Wrapper d = JsonConvert.DeserializeObject<Wrapper>(stringJson);
    

    And access your items with

    d.data.item
    

    Follow casing! In your json all properties start with a lower case letter, wheras in your Category class they are upper case. Alternatively you can define a contractresolver which ignores casing. See the docs on how that works.

    Follow types! In your json id and status are strings, in your Category class they are integers. You may be able to work around that with contract resolver too. See the docs for details.