How can I deserialize json dataset in .net core

I am trying to extract various elements from an api that returns json. The problem I am facing is getting properties from json as it is not always the same name. I used to deserialize json files, but they were different from this. Here's the json I have:

{"2": {"name": "Cannonball", "store": 5}, "6": {"name": "Cannon base", "store": 187500}, "12289": {"name": "Mithril platelegs (t)", "store": 2600}, "8": {"name": "Cannon stand", "store": 187500}, "10": {"name": "Cannon barrels", "store": 187500}, "12": {"name": "Cannon furnace", "store": 187500}}

      

It's actually a little more than that, but I can't figure out how easy it is to deserialize it since id has no real name, in the newtonsoft.json documentation I saw something about using datasets, I don't know if it really is this works, but I saw that they were removed. I would really like this to work, as it has bothered me quite a bit for quite some time.

If anyone knows how to do this, any help would be greatly appreciated.

+3


source to share


1 answer


You can handle this situation by deserializing to Dictionary<string, T>

, where T

is the class for storing item data, for example:

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

      

Deserialize:



var dict = JsonConvert.DeserializeObject<Dictionary<string, Item>>(json);

      

Fiddle: https://dotnetfiddle.net/hf1NPP

+7


source







All Articles