Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I deserialize a json dataset in .net core

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.

like image 843
jasont20015 Avatar asked Apr 26 '17 23:04

jasont20015


People also ask

How do I deserialize JSON in .NET core?

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.

How deserialize JSON works C#?

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.

What is serialize and deserialize in JSON?

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


1 Answers

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

like image 179
Brian Rogers Avatar answered Nov 22 '22 06:11

Brian Rogers