Deserialize JSON object with variable strings

I’m trying to deserialize a JSON response in c# using Newtonsoft.Json

Here is an example of the type of JSON response I’m working with:

{
  "version": "1.0",
  "fixes": [
    {
      "fix1": "this is fix 1",
      "fix2": "this is fix 2",
      "fix3": "this is fix 3"
    }
  ]
}

In this response there can be any number of "fixes."

My object class looks like this:

public class Update
{
    public class Fix
    {
        public IDictionary<string, string> Values { get; set; }
    }
    
    public class Root
    {
        public string version { get; set; }
        public List<Fix> fixes { get; set; }
    }
}

Here I’m deserializing the http response and trying to get value of fixes, but all of the values are null:

var root = JsonConvert.DeserializeObject<Update.Root>(strContent);
        
Update.Fix fixes = root.fixes[0];

foreach (var fix in fixes.Values)
{
    string test = fix.Value.ToString();
}

>Solution :

Eliminate the class Fix. In Root have public List<Dictionary<string, string>> fixes { get; set; }:

public class Root
{
    public string version { get; set; }
    public List<Dictionary<string, string>> fixes { get; set; }
}

Then, to loop through all the keys and values, you can use SelectMany() to project the list of dictionaries to an enumerable of key/value pairs:

foreach (var pair in root.fixes.SelectMany(p => p))
{
    Console.WriteLine($"{pair.Key}: {pair.Value}");
}

Demo fiddle here.

Leave a Reply