I need to parse a json string to Java object (i.e. Product) using Gson. Here is my problem : The json string of product will contain either list of Items(i.e. json array) or just an Item (i.e. json Object) with the same json key in both cases. How do I declare item variables in Product class to parse as follows? If I declare List then its failing in Object case and vice versa.
public class Product {
@SerializedName("item-content")
@Expose
private List<Item> itemsContent = null;
//OR
@SerializedName("item-content")
@Expose
private Item itemContent = null;
}
And here is how I'm converting json to model using gson.
public static <T> T getJavaObjectFromJsonString(String jsonString, Class<T> class1) {
T obj = null;
try {
obj = getGsonInstance().fromJson(jsonString, class1);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static Gson getGsonInstance() {
if (gson == null) {
gson = new GsonBuilder().setLenient().create();
}
return gson;
}
You have to use Gson custom parser:
And the parse your product object as follow: