How to parse JSONArray and JSONObject with the same json key using Gson?

808 Views Asked by At

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

There are 2 best solutions below

0
On

You have to use Gson custom parser:

public class Product implements JsonDeserializer<Product> {
    private List<Item> itemsContent = null;
    private Item itemContent = null;

    @Override
    public Product deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        Gson gson = new GsonBuilder().create();
        Product product = new Product();
        JsonElement itemsContent = jsonObject.get("item-content");
        if (itemsContent.isJsonObject()) this.itemsContent = gson.fromJson(itemContent, Item.class);
        else this.itemContent = gson.fromJson(itemsContent, new TypeToken<List<Item>>(){}.getType());
        return product;
    }
}

And the parse your product object as follow:

new GsonBuilder().registerTypeAdapter(Product.class, new Product()).create().fromJson(response.toString(), Product.class);
0
On

import com.google.gson.JsonObject;

import com.google.gson.JsonParser;

JsonParser jsonParser = new JsonParser();

JsonObject jsonObj = (JsonObject) jsonParser.parse(retValue); //retValue = JSONObject

why didn't you using Gson's JsonParser?