1

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?)

  • You can deserialize `items` into a `public Dictionary` or `public Dictionary` as shown in [How can I parse a JSON string that would cause illegal C# identifiers?](https://stackoverflow.com/a/24536564/3744182) or [Create a strongly typed c# object from json object with ID as the name](https://stackoverflow.com/a/34213724/3744182). – dbc Sep 11 '22 at 00:50

1 Answers1

0

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();
Serge
  • 40,935
  • 4
  • 18
  • 45