Home > Back-end >  Deserializing partial json content with RestSharp
Deserializing partial json content with RestSharp

Time:03-02

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?

CodePudding user response:

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?

CodePudding user response:

try this

   var jsonParsed = JObject.Parse(json);

    Root data;

    if (jsonParsed["data"] != null)
        data = jsonParsed.ToObject<Root>();
    else
    {
        data = new Root
        {
            Updated = (string)jsonParsed["updated"],
            Items = new Data
            {
                Categories = jsonParsed["categories"].ToObject<List<Category>>(),
                Products = jsonParsed["products"].ToObject<List<Dish>>()
            }
        };
    }
  • Related