Dan Dan - 23 days ago 7
JSON Question

Deserialize JSON to an array of objects, instead of to one object list

Apologies for the probably confusing title. I'm new to JSON and I'm working on a Web Application with a piece of software which interfaces with the API. I have control of both.

My applications needs to enumerate a list of "Clients" and their "Projects". Currently it returns the following:

{
"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"
}
]
}
]
}


I can deserialize this easily enough to an object using the following JSON.NET code:

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


However, this only works if my objects look like the following:

[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>();
}


(NB: I've changed the names of a lot of properties and objects for privacy, so apologies for any mistakes added)

What I really want to be able to do is use the following code:

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


But no matter how I format the JSON response, JSON.NET throws an error stating that the JSON is not an array. Can anyone advise where I'm going wrong, or what I'm misunderstanding?

Answer

Your JSON is an object, that contains a field that is an array. You cannot directly convert it to array.

You can use this JSON I suppose:

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

But seriously, it does not hurt to have a proper response object that contains an array inside. I would rather us it.