0

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;
}

}
Hashem
  • 31
  • 1
  • 6
  • you might need to use custom Adapter like this https://stackoverflow.com/questions/46568964/gson-deserialize-string-or-string-array – MyTwoCents Jan 08 '20 at 11:34
  • Thanks. A lot of insights from that question. but I worked out a very lazy yet beautiful solution.. check the answer @MyTwoCents – Hashem Jan 08 '20 at 21:21

1 Answers1

0

I defined value as of type Object so it can be cast somehow to whatever comes in the JSON. It worked!

Hashem
  • 31
  • 1
  • 6