0

I have a JSON file I'm trying to deserialize to a list with a dictionary as the values, but struggling with getting the output in a nice format and struggling to index/parse it once it's deserialized. I'm new to this and would appreciate the help. I would like the key/value pairs to look like: {"greeting" : ["greet1": "hey", "greet2" : "hi"]}

JSON file below:

{
"greeting": [
        {
          "greet1": "hey",
          "greet2": "hi"
        }
      ],
"bye": [
        {
          "bye1": "adios"
        }
      ]
}

Attempted code:

public static Dictionary<string, List<Dictionary<string, string>>> jsonResponses = new Dictionary<string, List<Dictionary<string, string>>>();

public static void DeserializeJsonDict()
{
    string jsonURL = HttpContext.Current.Server.MapPath("./theFile.json");

    using (var webClient = new System.Net.WebClient())
    {
        var jsonData = webClient.DownloadString(jsonURL);
        jsonResponses = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>>(jsonData);

    }

}
Avani Reddy
  • 1
  • 1
  • 1
  • do you want to to dynamically generate a class object as the input jsonstring? like : `Object{objGreeting{propGreeting1,propGreeting2},objBye{propBye1}}`? – Abdur Rahim Sep 26 '17 at 06:09
  • What is your problem? `JsonConvert.DeserializeObject>>>(jsonData)` works perfectly. See https://dotnetfiddle.net/V3NX3n for a demo. – dbc Sep 26 '17 at 06:10
  • Yes, it works, but I’m now struggling to index the output to pull out the values. How would I index the dictionary and the list within the dictionary? – Avani Reddy Sep 26 '17 at 06:34
  • 1
    Are you looking for [What is the best way to iterate over a Dictionary in C#?](https://stackoverflow.com/q/141088)? – dbc Sep 26 '17 at 06:47
  • JsonConvert.DeserializeAnonymousType(System.Uri.UnescapeDataString(str), new Dictionary()); – valerysntx Sep 26 '17 at 07:00
  • @AvaniReddy so the question is actually how to use the converted object? Maybe try JObject.Parse or JArray.Parse methods, that are made for such purposes – valerysntx Sep 26 '17 at 07:06

2 Answers2

0
var str = @"{'greeting':[{'greet1': 'hey','greet2': 'hi'}],'bye': [{'bye1': 'adios'}]}";    
var data = JsonConvert.DeserializeAnonymousType(str, new Dictionary<dynamic, dynamic>());

You can refer properties directly e.g. data.greeting. Also, there is one more approach to traverse convertion results - using KeyValuePair<string, dynamic> as generic type parameter gives you ability to iterate over dynamic values, e.g.

foreach (var i in data){
  Console.WriteLine(i.Key);
  foreach(var v in i.Value) Console.WriteLine(v); 
}

https://dotnetfiddle.net/UUvMeA

valerysntx
  • 506
  • 3
  • 7
-1
string json = @"{""key1"":""value1"",""key2"":""value2""}";

var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
noamt
  • 7,397
  • 2
  • 37
  • 59