I am making an Android native app that makes requests Using Retrofit2 to the WooCommerce API and gets the JSON responses mapping them with Model Classes (POJO) with the help of GSON. I use a plugin in Android Studio that generates the POJOs from JSON responses automatically.
When sending requests to the WC API, some end-points have this kind of responses:
"meta_data": [
{
"id": 2881,
"key": "wc_productdata_options",
"value": [
{
"_bubble_new": "\"yes\"",
"_bubble_text": "معجون أسنان",
"_custom_tab_title": "معجون أسنان Oral-B",
"_custom_tab": "",
"_product_video": "",
"_product_video_size": "",
"_product_video_placement": "",
"_top_content": "",
"_bottom_content": ""
}
]
},
{
"id": 3077,
"key": "_wp_page_template",
"value": "default"
}
]
The attribute value
can be either a String
or a List<Value>
but the POJO plugin defines value
as only List<Value>
So when parsing the response I get an error that GSON expects BEGIN_ARRAY but got STRING instead
when it reaches "value" : "default"
.
How can I represent that value
can be a string OR a list in the Model Class.
Here's the automatically generated POJO of meta_data
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class MetaDatum {
@SerializedName("id")
private Long mId;
@SerializedName("key")
private String mKey;
@SerializedName("value")
private List<Value> mValue;
public Long getId() {
return mId;
}
public void setId(Long id) {
mId = id;
}
public String getKey() {
return mKey;
}
public void setKey(String key) {
mKey = key;
}
public List<Value> getValue() {
return mValue;
}
public void setValue(List<Value> value) {
mValue = value;
}
}
I defined value
as of type Object
so it can be cast somehow to whatever comes in the JSON. It worked!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.