Search code examples
c#jsonjson.net

Is there a way to deserialize numbered JSON fields to a C# List field using Newtonsoft?


Example JSON:

{
    "name": "John Smith",
    "pet1_name": "Fido",
    "pet2_name": "Fluffy",
    "pet3_name": "Killer"
}

What I'm looking for is the simplest way to use Newtonsoft to deserialize this into an object that looks something like this:

public class Person {
    public string Name { get; set; }
    public List<string> PetNames { get; set; }
}

Preferably I'd like to avoid having to create individual properties called "Pet1Name", "Pet2Name", etc. and combine them into a list after deserialization, if that's possible.


Solution

  • You could deserialize the Json by adding a property of type Dictionary<string,object>, decorated with [JsonExtensionData] attribute. You could then make your PetNames property to fetch the values from the dictionary. For example,

    public class Person 
    {
        public string Name { get; set; }
        public List<string> PetNames => PetNamesDictionary?.Values.Select(x=>x.ToString()).ToList();
        
        [JsonExtensionData]
        public Dictionary<string,object> PetNamesDictionary{get;set;}
    }
    
    var result = JsonConvert.DeserializeObject<Person>(json);
    

    Output

    enter image description here