Simar Simar - 26 days ago 6
Android Question

Convert json into an object of a class that contains a template variable using gson

My Api response looks like this.

{
"status" : 1,
"message" : "Some Message",
"data" : {
}
}


My Response class looks like this. The type of data changes depending on the request being made.

public class Response<T>{
@Expose
@SerializedName("status")
private Integer status;

@Expose
@SerializedName("message")
private String message;

@Expose
@SerializedName("data")
private T data;

//Getters and Setters
}


Question 1. How to use gson to parse this json?

Response<ClassA> response = new Gson().fromJson(jsonString, ??);


Question 2. How would i write Parcelable implementation for this class.

dest.writeInt(status == null ? 0:status);
dest.writeString(message);
??

Answer

Answering my own question.

Question 1:

Response<ClassA> response = new Gson().fromJson(jsonString, new TypeToken<Response<ClassA>>(){}.getType());

Question 2:

Changed class to this.

public class Response<T extends Parcelable>{
@Expose
@SerializedName("status")
private Integer status;

@Expose
@SerializedName("message")
private String message;

@Expose
@SerializedName("data")
private T data;

//Getters and Setters

@Override
public void writeToParcel(Parcel dest, int flags) {
    if (data != null) {
        dest.writeString(data.getClass().getName());
        dest.writeParcelable(data, flags);
    } else dest.writeString(null);
    dest.writeString(message);
    dest.writeInt(status);
}
}

protected Response(Parcel in) {
    String className = in.readString();
    if (className != null) {
        try {
            data = in.readParcelable(Class.forName(className).getClassLoader());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    message = in.readString();
    status = in.readInt();
}