Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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."

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading