skip to Main Content

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();
}

2

Answers


  1. your fixes are a dictionary, not a collection, but you can convert it to a collecton

             List<string> fixes = JObject.Parse(json)["fixes"]
            .SelectMany(jo => ((JObject)jo).Properties()
            .Select(p => (string) p.Value))
            .ToList();
            
            foreach (string fix in fixes)
            {
                Console.WriteLine(fix);
            }
    

    output

    this is fix 1
    this is fix 2
    this is fix 3
    

    or dictionary

         Dictionary<string, string> fixes = JObject.Parse(json)["fixes"]
        .Select(jo => jo.ToObject<Dictionary<string, string>>())
        .FirstOrDefault();
    
        foreach (var fix in fixes)
        {
            Console.WriteLine(fix.Key + " : " + fix.Value);
        }
    

    output

    fix1 : this is fix 1
    fix2 : this is fix 2
    fix3 : this is fix 3
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search