Oliver Olmaru
Oliver Olmaru

Reputation: 3

C# deserializing weirdly formatted JSON array

I'm working on a client library for an accounting software. Communication is done via HTTP API, which return JSON responses. Till now JSON has been quite ordinary and translates easily into classes for Json.Net parsing. But there is a query, where it returns a very weird array - each array member has a title (which has no importance) and is treated like different object (100% identical members). Last time I was dealing with it, I wrote a little helper to remove the keys and replaced {} with [], but I wonder, if I can use Json.NET directly to parse this correctly.

I'm using latest stable Json.Net, .Net Framework 4.6 and deserialize using JsonConvert.DeserializeObject.

Json array, which doesn't parse

{
      ...
      "warehouses": {
        "1": {
          "warehouseID": 1,
          "totalInStock": 0,
          ...
        },
        "2": {
          "warehouseID": 2,
          "totalInStock": 0,
          ...
        },
        "3": {
          "warehouseID": 3,
          "totalInStock": 0,
          ...
        },
        "4": {
          "warehouseID": 4,
          "totalInStock": 0,
          ...
        }
      },
      ...
}

Classes

public class MainObject{
    ...
    public List<Warehouse> warehouses { get; set;}
    ...
}

public class Warehouse{
    public int warehouseID { get; set; }
    public string totalInStock { get; set; }  
    ...
}

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

Upvotes: 0

Views: 87

Answers (1)

Jota.Toledo
Jota.Toledo

Reputation: 28434

Thats not an array, its a key-value map. The corresponding class in C# would be a Dictionary<TKey,TValue>.

Refactor into the following:

public class MainObject{
    ...
    public Dictionary<int, Warehouse> warehouses { get; set;}
    ...
}

Upvotes: 8

Related Questions