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

时间:2016-11-14 09:16:21

标签: c# json json.net

为可能令人困惑的标题道歉。我是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不是数组。任何人都可以告诉我哪里出错了,或者我误解了什么?

2 个答案:

答案 0 :(得分:4)

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

但您仍然可以使用LINQ to JSON从JSON获取客户列表:

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

答案 1 :(得分:1)

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

我猜你可以使用这个JSON:

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

但严重的是,拥有一个包含内部数组的正确响应对象并没有什么坏处。我宁愿我们。