I need to parse Json into a class, Lots of Properties stay the same but there is one object which is dynamic based on the type of JSON that has been passed, For example, if it is Customer.json, I need to parse CustomerAttributes along with BaseResponse, if it Order.json, I need OrderAttributes along with BaseResponse. I know what type of Json is there beforehand.
Here is my code.
public abstract class BaseResponse
{
public int Id {get;set;}
public int Name {get;set;}
public CommonResponse metadata { get; set; }
}
public class CommonResponse
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
// I need CustomerAttributes here if I am parsing Customer.Json and
// OrderAttributes here if I am parsing Order.Json
}
public class Pagination
{
public int totalPages { get; set; }
public int number { get; set; }
public int size { get; set; }
}
public class CustomerAttributes
{
public int Age { get; set;}
public string Address { get; set;}
}
public class OrderAttributes
{
public int Amount { get; set;}
public DateTime startDate { get; set;}
public DateTime endDate { get; set;}
}
I am not able to figure out what should come in my CommonResponse class to parse both the attributes.
CodePudding user response:
There are a variety of ways to handle situations like this. Following are the ones I find myself using most often.
If the code that's calling into the parser can be aware of which type it needs, you can make the property generic:
public class CommonResponse<TAttributes>
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
public TAttributes attributes { get; set; }
}
On the other hand, if you don't know which type it might be until later, you can just use JObject (or the equivalent type for the JSON parsing library you're using), and deserialize that at the point where you know what type you expect:
public class CommonResponse
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
public JObject attributes { get; set; }
}