Morpheus
Morpheus

Reputation: 3523

Deserialize a JSON file which has nested dictionaries

I have the following JSON file,

 {
 "NAME": {
    "ABC": {
        "Score": 2, 
        "violations": []
    }, 
    "DEF": {
        "Score": 4, 
        "violations": []
    }, 

    "GHI": {
        "Score": 6, 
        "violations": ["badform"]
    }
  }

I am trying to deserilaize this by creating a class but I am finding it very difficult to construct the class as I am either getting nulls or JSON.net crashing. Could anyone tell me the best way to construct the deserializer?

Upvotes: 0

Views: 1193

Answers (1)

Surfin Bird
Surfin Bird

Reputation: 488

This should work (at least it works here if I add missing “}” to the end of JSON file):

using ParsedData = Dictionary<string, Dictionary<string, A>>;

class A {
    public int Score;
    public string[] violations;
}

var parsed = JsonConvert.DeserializeObject<ParsedData>(…);

Another version:

class A {
    public int Score;
    public string[] violations;
}

class B : Dictionary<string, A> {}
class C : Dictionary<string, B> {}

var parsed = JsonConvert.DeserializeObject<C>(…);

Upvotes: 2

Related Questions