Bullet
Bullet

Reputation: 87

How to convert json to Dictionary

I have to convert the JSON string to Dictionary< string, object >. For that, I am following something here https://www.programming-books.io/essential/csharp/collect-all-fields-of-json-object-5293c4c9342c403bb40dd9232692a7bc and doing DotNotation to convert it to Dictionary however, the output is not as expected.

JSON Data I am trying:

{
  "name": "Madame Uppercut",
  "age": 39,
  "secretIdentity": "Jane Wilson",
  "powers": [
    "Million tonne punch",
    "Damage resistance",
    "Superhuman reflexes"
  ],
  "accounting": [
    {
      "firstName": "John",
      "lastName": "Doe",
      "age": 23
    },
    {
      "firstName": "Mary",
      "lastName": "Smith",
      "age": 32
    }
  ]
}

Using the code from above link and converting from DotNotation as below

 var dictionary = new Dictionary<string, object>();
            foreach (var jsonInput in dotNotation)
            {
                var hierarchy = jsonInput.Key.Split('.');

                var bottom = dictionary;

                for (int i = 0; i < hierarchy.Length; i++)
                {
                    var key = hierarchy[i];

                    if (i == hierarchy.Length - 1)
                    {
                        bottom.Add(key, jsonInput.Value);
                    }
                    else
                    {
                        if (!bottom.ContainsKey(key))
                            bottom.Add(key, new Dictionary<string, object>());

                        bottom = (Dictionary<string, object>)bottom[key];
                    }
                }
            }

finally, the result is like.

enter image description here

Now, what I want is to group the arrays(powers and accounting). I know the JToken path is giving '[]' array path but I want it like below for power and account in the dictionary.

{[power, [{"Million tonne punch" }, {"Damage resistance" }, {"Superhuman reflexes"}]]}

Upvotes: 1

Views: 550

Answers (1)

Isaac Be
Isaac Be

Reputation: 81

Use Json.NET

var values = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

Upvotes: 2

Related Questions