I had similar scenario while consuming an API. what i had done was expose just a List<T>
property and internally in my implementation checked if the object coming is single or collection. Here is the code i had.
Use Object
type property for deserializing first.
private Object _leg;
[JsonProperty("Leg")]
public Object Leg
{
get => _leg;
set
{
_leg = value;
Legs = ParseLegs(value);
}
}
Then add property for List<CarDetails>
in your scenaion, i had Leg
and in getter i had logic like below:
[JsonIgnore]
public List<Leg> Legs { get; private set; }
private List<Leg> ParseLegs(object json)
{
// case for multiple legs in response
if (json is JArray array)
return array.ToObject<List<Leg>>();
if (!(json is JObject @object)) return new List<Leg>();
return new List<Leg>() { @object.ToObject<Leg>()};
}
}
Just replace in your case Leg
type to CarDetails
and it should be working good for you.
Your class structure would look like:
private Object _carDetail;
[JsonProperty("CarDetails")]
public Object CarDetail
{
get => _carDetail;
set
{
_carDetail = value;
CarDetails = ParseCarDetails(value);
}
}
and other property would be:
[JsonIgnore]
public List<CarDetails> CarDetails { get; private set; }
private List<CarDetails> ParseCarDetails(object json)
{
// case for multiple cardetails in response
if (json is JArray array)
return array.ToObject<List<CarDetails>>();
if (!(json is JObject @object)) return new List<CarDetails>();
return new List<CarDetails>() { @object.ToObject<CarDetails>()};
}
Hope it gives you helps.