I'm working on an ASP .NET core web api where I'm trying to create a model in C# based on a JSON that can have dynamic properties.
- The type field can be of 3 types: Land, Water, Air. Based on the type, the corresponding properties in the "source" would be different.
For example. if the type is "Land", there would be an additional property in source called "speed". If the type is "Air", there would be 2 additional properties in source called "Height" and "NumberLandings".
- The modify property is an array that can have different types of modifications - Performance/Aesthetic/Functional...., and based on the modification type, I can have different properties underneath for that modification.
For example, if the type is "Performance", there would be additional properties such as brakes/turbo/suspension.
{
"properties": {
"source": {
"type": "Land",
"speed": "160mph"
},
"modify ": [
{
"type": "Performance",
"brakes": "",
"turbo": "",
"suspension": ""
},
{
"type": "Functional",
"electric": "",
"applications": "Carplay"
}
]
}
}
Question: How can I construct my C# class/model for the dynamic JSON? I'm thinking to keep the source type and modification type as an enum, and based on the enum type, define the other parameters.
I don't want to define all the properties and end up having some of them as null, like below:
[DataContract]
public class Source
{
[DataMember]
[JsonProperty(PropertyName = "type")]
public string Type { get; set; }
[DataMember]
[JsonProperty(PropertyName = "speed")]
public string Speed{ get; set; }
[DataMember]
[JsonProperty(PropertyName = "height")]
public string Height{ get; set; }
[DataMember]
[JsonProperty(PropertyName = "NumberLandings")]
public string NumberLandings { get; set; }
}