Newtonsoft - Deserialize JSON Object With Numeric Keys

Viewed 43

I'm trying to deserialize a JSON document like the following:

{
    "items": {
        "0": {
            "name": "Item 1"
        },
        "1": {
            "name": "Item 2"
        }
    }
}

Into an object like:

public class Inventory
{
    public Item[] Items { get; set; }
}

public class Item
{
    public string Name { get; set; }
}

The items object should presumably be an array, however the data that I'm consuming uses an object, so I can always assume that they will be numeric values. What is the most efficient way to deserialize this? I am a Newtonsoft newbie and don't know where to start (should I extend a JsonConverter? Use a JsonTextReader directly?, something else?)

1 Answers

it is usualy used Dictionary in this case

Inventory inventory=JsonConvert.DeserializeObject<Inventory>(json);

public class Inventory
{
    [JsonProperty("items")]
    public Dictionary<string, Item> Items { get; set; }
}

or if you want a list

List<Item> items = ((JObject)JObject.Parse(json)["items"]).Properties()
               .Select(x => new Item { Name = (string)x.Value["name"] }).ToList();

//or shorter and you don't need a class

List<string> names = ((JObject)JObject.Parse(json)["items"]).Properties()
                            .Select(x => (string)x.Value["name"] ).ToList();
Related