Search code examples
c#jsonjson.netrestsharp

Deserializing partial json content with RestSharp


I'm using RestSharp for making requests and deserializing responses into C# models with NewtonsoftJsonSerializer. And I ran into the situation where I am getting 2 similar json strings.

First:

{  
   "updated": "",
   "data":{
       "categories":[...],
       "products": [...]
   }
}

Second:

{  
   "updated": "",
   "categories":[...],
   "products": [...]
}

For deserializing the first one I'm using the following C# model:

public class Root
{
    [JsonProperty("updated")] public string Updated{ get; set; }
    [JsonProperty("data")] public Data Items{ get; set; }
}

public class Data
{
    [JsonProperty("categories")] public List<Category> Categories { get; set; }
    [JsonProperty("products")] public List<Dish> Products { get; set; }
}

public class Category{...} 

public class Dish{...}

I now I can use Data class for deserializing the second json string. But I want to use one model for deserialising both of them. And deserializing first json into Data class obviously returns null. Basically I need only categories and products lists.

What should I change in my model to make it happen? Is there any attribute that can help?


Solution

  • If you define class like this and deserialize json responses into this class, you can have a single class but some fields will be null for each different response.

    public class Data
    {
        [JsonProperty("updated")] public string Updated{ get; set; }
        [JsonProperty("categories")] public List<Category> Categories { get; set; }
        [JsonProperty("products")] public List<Dish> Products { get; set; }
        [JsonProperty("data")] public Data Items{ get; set; }
    }
    

    If you don't want to do it as above, I think you should create a custom deserializer as it is described here: How to implement custom JsonConverter in JSON.NET?