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

Time:12-20

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.

CodePudding user response:

You could deserialize the Json by adding a property of type Dictionary<string,object>, decorated with enter image description here

CodePudding user response:

you can use a json parse method

var jasonObject=JObject.Parse(json);

var person = new Person
{
Name = (string)jsonObject["name"],
PetNames = jsonObject.Properties().Where(p => p.Name != "name").Select(p => (string)p.Value).ToList()
};

or you can use a json deserialization method ( not as flexible and fast, as the previous one )

var result = JsonConvert.DeserializeObject<JsonPerson>(json);

var person = new Person {Name=result.Name, 
PetNames=result.PetNamesExt?.Values.Select(x=>x.ToString()).ToList()};

classes

public class Person
{
    public string Name { get; set; }

    [JsonIgnore]
    public List<string> PetNames {get; set;}

}
public class JsonPerson : Person
{
    [JsonExtensionData]
    public Dictionary<string, object> PetNamesExt { get; set; }
}

output

{
  "Name": "John Smith",
  "PetNames": [
    "Fido",
    "Fluffy",
    "Killer"
  ]
}
  • Related