Skip to content Skip to sidebar Skip to footer

Deserialze Json With A Wrapper Keyword With Gson

I am using retroft and gson for request/response in my app. The json structure I get from server for json object is like: { 'data': { 'name': 'Rogelio Volkman', 'address': '27299

Solution 1:

"data" is a JSON array, that's why you need to use je.getJsonArray("data").

If you are using retrofit, then you can deserialise this JSON in POJO with a help of GSON Converter Factory. POJO you can create with a help of this site: http://www.jsonschema2pojo.org/

Good tutorial on retrofit for your needs is here: https://guides.codepath.com/android/Consuming-APIs-with-Retrofit

Solution 2:

Create a POJO class for the response i.e create a model class and use the @SerializedName annotation like below

publicclassData{
  @SerializedName("name")
   String name;
  @SerializedName("address")
   String address;
  @SerializedName("lat")
   double lat;
   .....
} 

And to deserialize all you have to do is use the below code

String dataString = responseObject.getString("data");
  Data[] dataArray = new Gson().fromJson(dataString,Data[].class);

Let me know if you have any doubts.

Solution 3:

Make two gson model classes -

ClassUserObject {
        @SerializedName("data")
        User user;
    }
    ClassUser {
        // User object
    }
    ClassUserArray {
         @Serialized("data")
         User[] list;
    }

    Object json = newJSONTokener(data).nextValue();
    if (json instanceofJSONObject) {
      //you have an objectnewGson().fromJson(json,UserObject.class); 
    } elseif (json instanceofJSONArray) {
       newGson.fromJson(json,UserArray.class);
    }

Solution 4:

its perfectly fine to do:

@Overridepublic DataObjectModel deserialize(JsonElement json, Type type,
                                           JsonDeserializationContext context)throws JsonParseException {

            JsonElementdata= ((JsonObject) json).get("data");
            if(data.isJsonArray()) {
               JsonArraydataArr= data.getAsJsonArray();
                //do smth with array
            } else {
                JsonObjectdataObj= data.getAsJsonObject();
                //do smth with object
            }
            ...

Post a Comment for "Deserialze Json With A Wrapper Keyword With Gson"