1

I am using GSON for parsing JSON String but there is key contains Json which is sometime object and sometimes array. So please help me for parse it to model class using gson.

Resonse with Array

{
   "key" : "test",
   "value" : [
                {
                  "id" : 1,
                  "name": "abc"
                },
                {
                  "id" : 2,
                  "name": "xyz"
                }
             ]
}

Resonse with Object

{
   "key" : "test",
   "value" : {
                 "id" : 1,
                 "name": "abc"
             }
}

MyModel.java

public class MyModel implements Serializable {
@SerializedName("key")
@Expose
public String key;

@SerializedName("value")
@Expose
public ArrayList<ValueModel> value;

public class ValueModel implements Serializable {
    @SerializedName("id")
    @Expose
    public String id;

    @SerializedName("name")
    @Expose
    public String name;
   }
}

But it always goto in exeption because of datatype array and object I also tried with JsonDeserializer but i think i didnt implement it well So please help me to resolve it and parse json

Sandip Patel
  • 1,003
  • 1
  • 8
  • 15

4 Answers4

1

Simple try to access as Object then check the instanceof Object and parse data based on that

String json="";

JSONObject jsonMain=new JSONObject(json);

Object objectType=jsonMain.get("value");
  if (objectType instanceof JSONObject) {
    JSONObject jsonObjectType=(JSONObject)objectType;
  } else if (json instanceof JSONArray) {
    JSONArray jsonArrayType=(JSONArray)objectType;
  }

If you are using JSONObject

  if (objectType  instanceof JSONObject) {
     UserDetails details = new Gson().fromJson(objectType, UserDetails.class);

 } else if (objectType  instanceof JSONArray) {
     Type listType = new TypeToken<List<UserDetails>>() {
     }.getType();
     List<UserDetails> list = new Gson().fromJson(objectType, listType);
     userDetailsList.addAll(list);
 }
MJM
  • 5,119
  • 5
  • 27
  • 53
  • I got your answer but according to it i determine it only it is object or array but i want to convert object to array if. And this functionality provides by GSON. Please take a look at https://stackoverflow.com/questions/7668507/gson-handle-object-or-array – Sandip Patel May 22 '18 at 10:36
  • I want to handle it into model itself – Sandip Patel May 22 '18 at 10:36
  • @SandipPatel i have updated the answer,you need t use mixture of both model handling and manual parsing,because JSONResponse is not fixed – MJM May 22 '18 at 10:41
0

Add SerializedName name for object also and add custom getter

public class MyModel implements Serializable {
      @SerializedName("key")
      @Expose
      public String key;

      @SerializedName("value")
      @Expose
      public ArrayList<ValueModel> valueList;

      @SerializedName("value")
      @Expose
      ValueModel modelValue;

      public List<ValueModel> getValueModel() {
          return Collections.singletonList(modelValue);
       }

public class ValueModel implements Serializable {
        @SerializedName("id")
        @Expose
        public String id;

        @SerializedName("name")
        @Expose
        public String name;
       }
     }
Sam Raju
  • 189
  • 8
  • I want to convert object to array if there is object and if array then its ok. – Sandip Patel May 22 '18 at 10:28
  • It can be done by using JsonDeserializer or JsonAdapter but i dont know how to implement it. If you know then please help me to implement it. Thanks. – Sandip Patel May 22 '18 at 10:31
  • i update my answer please check that, You can also use `public List getValueModel () { return Arrays.asList(modelValue); }` – Sam Raju May 22 '18 at 10:37
  • You have used two different object for single key "value". But GSON provides JsonAdapter or JsonDeserializer for that but i cant understand it well. please refer this link https://stackoverflow.com/questions/7668507/gson-handle-object-or-array – Sandip Patel May 22 '18 at 10:40
  • Thank you for give me a new valuable information. you can use JsonAdapter ( like the link you posted ) to solve your problem. – Sam Raju May 22 '18 at 10:46
  • But i didn't get it well they used it at the time of parsing but i want to use it inside model. – Sandip Patel May 22 '18 at 10:57
  • did you try my method?? – Sam Raju May 22 '18 at 11:01
  • In GSON there is annotation available @JsonAdapter. It must be used JsonAdapter class for deserialization. But how ? i don't know? – Sandip Patel May 22 '18 at 11:06
0

You can try:

gson.fromJson(jsonString, classOfModel)

And I think you can remove @SerializedName and @Expose tags.

Duong Anh
  • 529
  • 1
  • 4
  • 21
0

In Case you didn't find the answer. Check this.

public class SomeModel  {

    @SerializedName("my_model")
     private MyModel[] myModel;

    public List<MyModel> getMyModel() {

       return new LinkedList<MyModel>( Arrays.asList(myModel));

    }

     public static class MyModelDeserializer implements JsonDeserializer<MyModel[]> {

    @Override
     public MyModel[] deserialize(JsonElement json, Type typeOfT,
     JsonDeserializationContext context) throws JsonParseException {

      if (json instanceof JsonArray) {

            return new Gson().fromJson(json, MyModel[].class);

      }

      MyModel child = context.deserialize(json, MyModel.class);

         return new MyModel[] { child };
      }
  }
}

reference: https://nayaneshguptetechstuff.wordpress.com/2014/06/21/parsing-json-with-gson-sometimes-object-sometimes-array/

Alireza Nezami
  • 515
  • 4
  • 12