Search code examples
c#apirestjson-deserialization

Deserialising JSON made up of various models C#


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?


Solution

  • 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.