0

I have some JSON being sent to me that looks like this:

{"MessageCodes": {
      "Code1": "Message 1",
      "Code2": "Message 2",
      "Code3": "Message 3",
      "Code4": "Message 4",
      "Code5": "Message 5",
      "Code6": "Message 6",
}}

This is saying there is an object called MessageCodes which contains many other objects within it (Code1, Code2, etc...). The object names, Code1, Code2,... are just example object names. The JSON I am receiving contains hundreds of objects contained within the MessaageCodes object. All are name value pairs.

I am using JSON.net by Newtonsoft to deserialize the JSON sent to me. Does anyone know how I can deserialize the above JSON into a Dictionary?

tentmaking
  • 2,076
  • 4
  • 30
  • 53
  • What you've posted is not valid JSON, so it couldnt be parsed into a dictionary. It appears that you need to specify your object (class) name, then `MessageCodes` would be a dictionary property on that class. – crthompson May 18 '15 at 21:54
  • 1
    possible duplicate of [How can I deserialize JSON to a simple Dictionary in ASP.NET?](http://stackoverflow.com/questions/1207731/how-can-i-deserialize-json-to-a-simple-dictionarystring-string-in-asp-net) – Cory Nelson May 18 '15 at 21:54
  • Oops, simple mistake with the improperly formatted JSON. Hopefully people can still understand the question being asked... Thanks – tentmaking May 19 '15 at 17:13

2 Answers2

2

First of all, your JSON is not properly formatted. If it represents an object, it should be wrapped in outer braces:

var json = @"{'MessageCodes': {
  'Code1': 'Message 1',
  'Code2': 'Message 2',
  'Code3': 'Message 3',
  'Code4': 'Message 4',
  'Code5': 'Message 5',
  'Code6': 'Message 6'}}";

var dict = JsonConvert.DeserializeObject<Test>(json);

public class Test
{
    public Dictionary<string, string> MessageCodes { get; set; }
}
David L
  • 32,885
  • 8
  • 62
  • 93
0

Using Newtonsoft.Json you can do next:

   var jsonString = @"{'MessageCodes': {'Code1': 'Message 1','Code2': 'Message 2','Code3': 'Message 3'}";
   var dictionary = JsonConvert.DeserializeObject<JObject>(jsonString)
                .GetValue("MessageCodes")
                .ToDictionary(x => x.First.Path, x => x.First.Value<string>());
rnofenko
  • 9,198
  • 2
  • 46
  • 56