如何反序列化JSON数据? C# [英] How to Deserialize JSON data? C#

查看:111
本文介绍了如何反序列化JSON数据? C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从API获取Json数据,而我一直在尝试反序列化.

Im getting a Json Data from an API and i have been trying to deserialize.

Json数据:

{
   "items": [
      {
         "id": "1",
         "name": "samplename",
         "AddressList1": {
            "City": "Hyd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      },
      {
         "id": "2",
         "name": "samplename2",
         "AddressList1": {
            "City": "Hydd",
            "State": "TN",
            "Country": "IN"
         },
         "Age": "10"
      }
   ],
   "paging": {
      "cursors": {}
   }
}

实体:

public class AddressList1
{
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
}

public class Item
{
    public string id { get; set; }
    public string name { get; set; }
    public AddressList1 addressList1 { get; set; }
    public string Age { get; set; }
}

public class Cursors
{
}

public class Paging
{
    public Cursors cursors { get; set; }
}

public class Users
{
    public List<Item> items { get; set; }
    public Paging paging { get; set; }
}

C#代码:

JsonConvert.DeserializeObject<List<Users>>(content);

错误消息:

无法反序列化当前JSON对象(例如{"name":"value"}) 进入类型'System.Collections.Generic.List`1 [Entities.Users]' 因为该类型需要JSON数组(例如[1,2,3])进行反序列化 正确.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Entities.Users]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

我在哪里做错了?

推荐答案

以下是JSON对象;您的情况是User

The following is a JSON-object; in your case a User

{ ... }

以下是JSON数组;在您的情况下,User

The following is a JSON-array; in your case an array of User

[ { ... }, { ... } ]

因此,如果要反序列化进入用户数组的JSON,则不可能,因为JSON中没有数组.

Thus if you want to deserialize the JSON you got into an array of Users this is not possible because you have no array in JSON.

因此反序列化的正确代码是:

Therefore the right code to deserialize is:

JsonConvert.DeserializeObject<Users>(content);

此外,您的映射是错误的,因为在JSON中有一个属性AddressList1,在类中它称为addressList1

Furthermore your mapping is erroneous because in JSON there is a property AddressList1 and in the class it is called addressList1

这篇关于如何反序列化JSON数据? C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆