I am working on a back end data integration between an ERP system and Shopify using their rest API. Recently I came across what I see as an inconsistency and I’m not certain how to handle this in C sharp without too much duplication. Specifically this relates to their admin API and the product API.
What I did is I took the Jason response from an API that invokes a return of a list of products and I got this class structure (I’m going to keep it simple by showing only the root and the main products property)
public class Root
{
public List<Product> products { get; set; }
}
However there is another API that allows you to get a single product an its return response does not utilize a list but a single subclass that is the same as the product subclass.
public class Root
{
public Product product { get; set; }
}
Everything else about the overall product class is the same. The only difference is that in one return we have a list of subclass product in the other a single element. Without having to create two completely different classes is there a way to do this so the rest of the subclass definitions which includes other properties and subclasses can be used. This is the subclass product:
public class Product
{
public Int64 id { get; set; }
public string title { get; set; }
public string body_html { get; set; }
public string vendor { get; set; }
public string product_type { get; set; }
public DateTime? created_at { get; set; }
public string handle { get; set; }
public DateTime? updated_at { get; set; }
public DateTime? published_at { get; set; }
public object template_suffix { get; set; }
public string published_scope { get; set; }
public string tags { get; set; }
public string admin_graphql_api_id { get; set; }
public List<Variant> variants { get; set; }
public List<Option> options { get; set; }
public List<Image> images { get; set; }
public Image image { get; set; }
}
I looked at inheritance but that didn’t seem to quite fit and I wasn’t certain if even extends would work and while my work around is too not use the get single product API but get a list of 1, I’m curious if there’s a way to do this where I can not have to create two full classes just because in the root one is a list and one is a single object.
I am using Newton json to do the serialization and deserialization of the object data.
2
Answers
You can have two classes with different names. When you deserialize the json, it will not matter what the root class is called.
Or, you could have a single root class with both the list property and the single instance property. When the deserialization is done, just access the appropriate property.
You could use inheritance:
When you need to deserialize, use:
Or