Converting json to c# object

*爱你&永不变心* 提交于 2019-12-25 03:13:34

问题


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?


回答1:


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.




回答2:


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 



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/51217014/converting-json-to-c-sharp-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!