0

I'm trying to work out how to deserialise a JSON response that can be made up of single or multiple models, so for instance, I have the following URL and Response from that endpoint:

https://api.site.com/products?query=fruit

Which would return something such as this:

{
    "fruit": [{ ... },{ ... }]
}

"Fruit" could be anything, but as an alternative, you can also do this:

https://api.site.com/products?query=fruit,pies

{
    "fruit": [{ ... }, { ... }],
    "pies": [{ ... }, { ... }]
}

So I know how to handle just one of the "selections" provided at a time, however how do I go about deserialising the response when there can be 2 separate models in the same response?

MrDKOz
  • 207
  • 2
  • 11
  • How did you deserialize fruit with its children? Apply the same technique to fruit's parent. – Jasen May 28 '21 at 19:54

1 Answers1

1

In case you know the json model before hand (also called data contract), then you can create a dedicated class. So, for the above scenario, the class would be

public class AnyClassName
{
    public List<Fruit> Fruit { get; set; }
    public List<Pie> Pie { get; set; }
}

And then use

Newtonsoft.Json.JsonConvert.DeserializeObject<AnyClassName>(jsonString)

In case you are not aware of the data-contract, then use

Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString)

In this case you have to do a lot of coding to probe for the existence of an element and extract the value.

Prem
  • 303
  • 2
  • 9
  • The difficulty comes in that there isn't just "Fruit" and "Pies", there's around 30 different combos of things you can request, so I couldn't make a model for each potential set of selections. – MrDKOz May 28 '21 at 22:48
  • 1
    If you know the data structure of 30 models, I would advice to go with structured approach, the first option. Saves a lot of time in deserialization. – Prem May 29 '21 at 06:50