将JSON反序列化为一个对象数组,而不是一个对象列表



为可能令人困惑的标题道歉。我是JSON的新手,我正在用一个与API接口的软件开发一个Web应用程序。两者我都有。

我的应用程序需要枚举"客户"和他们的"项目"的列表。当前它返回以下内容:

{
  "clients": [
    {
      "client_id": "1",
      "client_name": "Client1",
      "projects": [
        {
          "client_project_id": "1",
          "client_project_title": "WidgetsA",
          "client_project_client": "1",
          "client_project_status": "1"
        },
        {
          "client_project_id": "11",
          "client_project_title": "WidgetsB",
          "client_project_client": "1",
          "client_project_status": "1"
        }
      ]
    },
    {
      "client_id": "11",
      "client_name": "Client11",
      "projects": [
        {
          "client_project_id": "31",
          "client_project_title": "Install",
          "client_project_client": "11",
          "client_project_status": "1"
        }
      ]
    },
    {
      "client_id": "21",
      "client_name": "Client21",
      "projects": [
        {
          "client_project_id": "61",
          "client_project_title": "Marketing",
          "client_project_client": "21",
          "client_project_status": "1"
        }
      ]
    },
    {
      "client_id": "31",
      "client_name": "Client31",
      "projects": [
        {
          "client_project_id": "71",
          "client_project_title": "Fire Everyone",
          "client_project_client": "31",
          "client_project_status": "1"
        },
        {
          "client_project_id": "81",
          "client_project_title": "Buy A Company",
          "client_project_client": "31",
          "client_project_status": "1"
        }
      ]
    }
  ]
}

我可以很容易地使用以下JSON将其反序列化为对象。NET代码:

MyObject result = JsonConvert.DeserializeObject<MyObject>(response);

然而,只有当我的对象看起来像下面这样时,这才有效:

  [Serializable, JsonObject]
    internal class MyObject
    {
        [JsonProperty("clients")]
        internal List<ClientObject> ClientList = new List<ClientList>();
    }

 internal class ClientObject
    {
        [JsonProperty("client_id")]internal string ClientID { get; set; }
        [JsonProperty("client_name")] internal string ClientName { get; set; }
        [JsonProperty("projects")] internal List<ProjectObject> ProjectList = new List<ProjectObject>();
    }

(注:我已经改变了很多属性和对象的名称为隐私,所以为添加的任何错误道歉)

我真正想做的是使用下面的代码:

List<ClientObject> result = JsonConvert.DeserializeObject<List<ClientObject>>(response);

但是不管我如何格式化JSON响应,JSON。. NET抛出一个错误,指出JSON不是数组。谁能告诉我哪里错了,或者我误解了什么?

正如其他人所提到的,您的JSON是一个对象,而不是数组,因此它不能直接反序列化为列表。

但是你仍然可以使用LINQ to JSON从JSON中获取你的客户端列表:

string json = @"...";
JObject data = JObject.Parse(json);
List<ClientObject> clients = data["clients"].Select(c => c.ToObject<ClientObject>()).ToList();

JSON是一个对象,它包含一个数组字段。不能直接转换为数组。

你可以使用这个JSON:

[
    {
      "client_id": "1",      
    },
    {
      "client_id": "2",      
    }
]

但是说真的,拥有一个包含数组的适当响应对象并没有什么坏处。

相关内容

  • 没有找到相关文章

最新更新