Reputation: 644
Suppose I have a json response(see image) with an element "meta_data". Now the peculiar thing about this meta_data list is that it may or may not exist, depending upon if it has child elements. Not just this if it has only one child element then it will be shown as an object (key-value), instead of a list. So how can I model this element in my model Class, so that my app does not crash with errors like "Expected a string but was BEGIN_OBJECT at line 1 column 4864 path $[0].meta_data[0].value". Below is snipppet of my model class:
public class ProductModel {
private List<MetaDatum> meta_data = null;
public List<MetaDatum> getMetaData() {
return meta_data;
}
public void setMetaData(List<MetaDatum> meta_data) {
this.meta_data = meta_data;
}
// further more elements
}
Upvotes: 1
Views: 59
Reputation: 904
You can use following code
public class ProductModel {
private Object meta_data = null;
...
}
And cast it based on the response you received using instanceof keyword, Like
if(response instanceof List){
//iterate list.
}
if(response instanceof Object){
//use object.
}
Upvotes: 1