Deserialize JSON to nested C# Classes

Your problem is twofold:

  1. You don’t have a class defined at the root level. The class structure needs to match the entire JSON, you can’t just deserialize from the middle.
  2. Whenever you have an object whose keys can change, you need to use a Dictionary<string, T>. A regular class won’t work for that; neither will a List<T>.

Make your classes like this:

class RootObject
    public Results Results { get; set; }

class Results
    public Dictionary<string, JobCode> JobCodes { get; set; }

class JobCode
    public string StatusCode { get; set; }
    public string StatusMessage { get; set; }
    public string Id { get; set; }
    public string Name { get; set; }

Then, deserialize like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

Working demo here

Leave a Comment