How can I deserialize a json dataset in .net core

18,117

You can handle this situation by deserializing into a Dictionary<string, T> where T is a class to hold the item data, for example:

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

Deserialize like this:

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

Fiddle: https://dotnetfiddle.net/hf1NPP

Share:
18,117
jasont20015
Author by

jasont20015

Updated on June 13, 2022

Comments

  • jasont20015
    jasont20015 about 2 years

    I'm trying to fetch different items from an api, which returns a json. The problem I'm having is getting the properties from the json since it isn't always the same name. I've deserialized json files before, but they were different from this one. 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 bigger then this, but I can't figure out how to easily deserialize it, since the id doesn't have a real name, on the documentation of newtonsoft.json I saw something about using datasets, I don't know if that'd actually work but I've seen they have been removed. I'd really love to get this working since it's kinda been bothering me for quite some time now.

    If there's anyone who knows how to do this, any help would be greatly appreciated.