Search code examples
c#jsonjson.netdeserialization

Netwonsoft JSON deserialize into List with named entries


I want to deserialize this JSON:

{
  "Home1": [
    {
      "name": "Hans",
      "age": 20
    },
    {...}
  ],
  "Home2": [
    {...},
    {...}
  ]
}

into an List<House> with these classes:

class Person {
  public string Name { get; set; }
  public int Age { get; set; }
}
class House : List<Person> {
  public string Name { get; set; }
}

How can I tell Newtonsoft JSON that House.Name should be for the key (Home1)?

PS: The class structure is not fixed, but I need the name of the house to be a property in a class.


Solution

  • Leaving behind the rational behind the idea of inheriting a list and your class structure you surely can create custom converter but I would argue much easier option would be to deserialize json into Dictionary<string, House> (which can represent your json structure) and then manually map the names:

    var result = JsonConvert.DeserializeObject<Dictionary<string, House>>(json);
    foreach (var kvp in result)
    {
        kvp.Value.Name = kvp.Key;
    }
    
    var houses = result.Values;