简体   繁体   English

将JSON转换为C#对象

[英]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 我有一个API,可向我返回一个包含有关数据转换信息的json和一个包含数据的数组

{
    "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 Main.cs

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

my string stringJson gets the following value 我的字符串stringJson得到以下值

"\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 ... 错误:无法将当前json对象(例如{“ name”:“ value”})反序列化为类型...

How can I create an array of objects with json data? 如何使用json数据创建对象数组? 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"); 我是否可以单独地正式检索值,例如,我创建了一个变量bool status = jsonConvert.get(“ status”); something like that? 这样的东西?

Frist you outer JSON format is an object, not an array. 首先,您的外部JSON格式是对象,而不是数组。

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 反序列化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> . 您的json不仅包含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. 在您的json中,所有属性均以小写字母开头,而Category类中的大写字母则为大写。 Alternatively you can define a contractresolver which ignores casing. 或者,您可以定义一个忽略大小写的Contractresolver。 See the docs on how that works. 请参阅有关其工作原理的文档。

Follow types! 按照类型! In your json id and status are strings, in your Category class they are integers. 在您的json idstatus是字符串,在Category类中,它们是整数。 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 : 或者,您可以使用属性控制序列化,以使属性名称与.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: 反序列化json字符串的代码:

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 从Nuget安装Newtonsoft.Json,然后尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM