0

I have json response comming from service. For one element some time it is coming as json array and some time it is coming is json object.

Example:

Response 1:
{"_id":2,"value":{id: 12, name: John}}
Response 2:
{"_id":1,"value":[{id: 12, name: John}, {id: 22, name: OMG}]}

Here value is jsonObject in Response 1 and jsonArray in Response 2.

Problem is I am using Gson to parse the json. and kept the value as ArrayList in my POJO class.

public class ResponseDataset {
    private int _id;
    private ArrayList<Value> value;

    // getter setter
}

public class Value {
    private int id;
    private String name;

    // getter setter
}

Is there is any way I can handle this using Gson. My json response too large and complex so wanted to avoid line by line parsing.

k_g
  • 4,333
  • 2
  • 25
  • 40
Nitesh V
  • 381
  • 6
  • 18

2 Answers2

2

Even I had the same problem, I've done as the following.

    String jsonString = "{\"_id\":1,\"value\":[{id: 12, name: John}, {id: 22, name: OMG}]}";
    JSONObject jsonObject = new org.json.JSONObject(jsonString);
    ResponseDataset dataset = new ResponseDataset();
    dataset.set_id(Integer.parseInt(jsonObject.getString("_id")));
    System.out.println(jsonObject.get("value").getClass());
    Object valuesObject = jsonObject.get("value");
    if (valuesObject instanceof JSONArray) {
        JSONArray itemsArray =(JSONArray) valuesObject;
        for (int index = 0; index < itemsArray.length(); index++) {
            Value value = new Value();
            JSONObject valueObject = (JSONObject) itemsArray.get(index);
            value.setId(Integer.parseInt(valueObject.getString("id")));
            value.setName(valueObject.getString("name"));
            dataset.getValue().add(value);
        }
    }else if(valuesObject instanceof JSONObject){
        Value value = new Value();
        value.setId(Integer.parseInt(((JSONObject)valuesObject).getString("id")));
        value.setName(((JSONObject)valuesObject).getString("name"));
        dataset.getValue().add(value);
    }

You can try this.

Pasupathi Rajamanickam
  • 1,982
  • 1
  • 24
  • 48
1

Found the solution here Gson handle object or array

@Pasupathi your solution is also correct but I want a way using Gson as my service response is too large and complex.

Community
  • 1
  • 1
Nitesh V
  • 381
  • 6
  • 18