Search code examples
c#jsondictionaryjson-deserialization

How do I deserialize JSON into a C# Dictionary?


Problem

Heres my JSON object:

{
    "1000":{
               "id": "23445",
               "latlon": "6780" 
           },
    "1001":{
               "id": "23454",
               "latlon": "6784" 
           },
    "1002":{
               "id": "23245",
               "latlon": "6180" 
           },
    "1003":{
               "id": "12345",
               "latlon": "6740" 
           }
}

As you can see the property names are pure integers (1000, 1001, 1002, 1003)

I can't declare class variable names in integar and run System.json.Serialization.

Therefore I need to load the JSON file into:

public static Dictionary<int, NodeDetail> NodeInfo;

public class NodeDetail {
    public ulong id;
    public int latlon;

    //Generic class serializer

    //Generic class deserializer
}

Is there a library function for this? or do I have to parse the JSON string from ground up?

ps. I'm new to C#(coming from C++)


Solution

  • Newtonsoft.Json. You can pull it from NuGet.

    Simple example:

    public static T DeserializeJson<T>(string json)
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
    

    and then

    Dictionary<string, object> foo = DeserializeJson<Dictionary<string, object>>(" ... insert JSON here ... ");
    

    EDIT: given the structure you mention in your question, you may want to deserialize into a nested dictionary:

    Dictionary<int, Dictionary<long, int>> foo = DeserializeJson<Dictionary<int, Dictionary<long, int>>>(" ... insert JSON here ...");
    

    There's also JObject (in the same Newtonsoft.Json library) which is very helpful for deserializing to something uniform that can be used.