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.
NET objects (deserialize) A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it creates a JavaScriptSerializer instance and calls Deserialize() by passing JSON data. It returns a custom object (BlogSites) from JSON data.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With