简体   繁体   中英

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 (eg {"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?

Frist you outer JSON format is an object, not an array.

You models will like this.

public class Item
{
    public string id { get; set; }
    public string descricao { get; set; }
    public string observacao { get; set; }
    public string status { get; set; }
}

public class Data
{
    public List<Item> item { get; set; }
    public int count { get; set; }
}

public class Category
{
    public string code { get; set; }
    public bool result { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}

Deserialize json

var Data = JsonConvert.DeserializeObject<Category>(stringJson);
List<Item> items = Data.data.item;
//items get info from items 

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.

As an alternative, you can control the serialization using attributes, in order to keep your property names consistent with the general naming conventions used in the .NET Framework :

public class Item
{
    [JsonProperty("id")]
    public string Id { get; set; }

    [JsonProperty("descricao")]
    public string Descricao { get; set; }

    [JsonProperty("observacao")]
    public string Observacao { get; set; }

    [JsonProperty("status")]
    public string Status { get; set; }
}

public class Data
{
    [JsonProperty("item")]
    public List<Item> Items { get; set; }

    [JsonProperty("count")]
    public int Count { get; set; }
}

public class Response
{
    [JsonProperty("code")]
    public string Code { get; set; }

    [JsonProperty("result")]
    public bool Result { get; set; }

    [JsonProperty("message")]
    public string Message { get; set; }

    [JsonProperty("data")]
    public Data Items { get; set; }
}

Code to deserialize the json string:

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

Response response = JsonConvert.DeserializeObject<Response>(json);

Install Newtonsoft.Json from Nuget then Try it

string JsonData = "\r\n\r\n{\"code\":\"200\",\"result\":true,\"message\":\"\",\"data\":{\"item\":[{\"id\":\"5\",\"descricao\":\"TesteDesc\",\"observacao\":\"TesteObs\",\"status\":\"1\"}],\"count\":2}}";
JObject jobject = (JObject)JsonConvert.DeserializeObject(JsonData);

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