0

I am getting a different response for our WEB API as shown below:

Format 1 :

{
    "Data": {
        "CarDetails": {
            a
        }
    }
}

Format 2 :

{
    "Data": {
        "CarDetails": [
            {
                a
            },
            {
                b
            }
        ]
    }
}

For the first one, we were using properties like:

Format 1:

public CarDetails CarDetails { get; set; }

Format 2:

public List<CarDetails> CarDetails { get; set; }

So is there a way to handle this type of code dynamically in the properties section?

Connor Low
  • 5,900
  • 3
  • 31
  • 52

1 Answers1

0

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.

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • Thanks everyone for answering . Got this fixed from below link : https://stackoverflow.com/questions/18994685/how-to-handle-both-a-single-item-and-an-array-for-the-same-property-using-json-n – Sai Chaitanya May 14 '20 at 15:17