Skip to content Skip to sidebar Skip to footer

Retrofit 2.0 Parse Dynamic Json From Same Pojo Class

What I Have I have a server success response { 'response_code': 200, 'status': 'success', 'message': 'enqiry chat fetched successfully', 'meta_data': { 'count': '6' }

Solution 1:

My solution is to use some thing like this ,

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

publicclassResponse {

    @SerializedName("response_code")
    @ExposeprivateInteger responseCode;
    @SerializedName("status")
    @ExposeprivateString status;
    @SerializedName("meta_data")
    @ExposeprivateMetaData metaData;
    @SerializedName("data")
    @ExposeprivateList<Object> data = null;
    @SerializedName("message")
    @ExposeprivateString message;

    publicIntegergetResponseCode() {
        return responseCode;
    }

    publicvoidsetResponseCode(Integer responseCode) {
        this.responseCode = responseCode;
    }

    publicStringgetStatus() {
        return status;
    }

    publicvoidsetStatus(String status) {
        this.status = status;
    }

    publicMetaDatagetMetaData() {
        return metaData;
    }

    publicvoidsetMetaData(MetaData metaData) {
        this.metaData = metaData;
    }

    publicList<Object> getData() {
        return data;
    }

    publicvoidsetData(List<Object> data) {
        this.data = data;
    }

    publicStringgetMessage() {
        return message;
    }

    publicvoidsetMessage(String message) {
        this.message = message;
    }


    publicclassMetaData {

        @SerializedName("count")
        @ExposeprivateInteger count;

        publicIntegergetCount() {
            return count;
        }

        publicvoidsetCount(Integer count) {
            this.count = count;
        }

    }
 }

And use a Custom Array Adapter with Gson,

ArrayAdapter class

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

publicclassArrayAdapterFactoryimplementsTypeAdapterFactory {

    @Override@SuppressWarnings({"unchecked", "rawtypes"})public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

        TypeAdapter<T> typeAdapter = null;
        try {
            if (type.getRawType() == List.class || type.getRawType() == ArrayList.class) {

                typeAdapter = newArrayAdapter(gson,
                        (Class) ((ParameterizedType) type.getType())
                                .getActualTypeArguments()[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return typeAdapter;

    }

}

ArrayAdapterFactory class

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


classArrayAdapter<T> extendsTypeAdapter<List<T>> {

    private Class<T> adapterclass;
    private Gson gson;

    publicArrayAdapter(Gson gson, Class<T> adapterclass) {
        this.adapterclass = adapterclass;
        this.gson = gson;
    }

    @Overridepublic List<T> read(JsonReader reader)throws IOException {

        List<T> list = newArrayList<T>();

        finalJsonTokentoken= reader.peek();
        System.out.println(token);
        // Handling of Scenario 2( Check JavaDoc for the class) :if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
                token == JsonToken.BOOLEAN) {
            Tinning= (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } elseif (token == JsonToken.BEGIN_OBJECT) {
            // Handling of Scenario 1(Check JavaDoc for the class) :Tinning= (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } elseif (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            while (reader.hasNext()) {
                @SuppressWarnings("unchecked")Tinning= (T) gson.fromJson(reader, adapterclass);
                list.add(inning);
            }
            reader.endArray();
        }

        return list;
    }

    @Overridepublicvoidwrite(JsonWriter writer, List<T> value)throws IOException {

    }
}

And register the adapter factory like this,

Gsongson=newGsonBuilder().registerTypeAdapterFactory(newArrayAdapterFactory()).create();

This will help to deserialise the json string.

Post a Comment for "Retrofit 2.0 Parse Dynamic Json From Same Pojo Class"