2 Years ago we did a project in which we had to handle notifications data with different type of objects in same array we handle that while using retrofit
this is our retrofit Creator
class
class Creator {
public static FullTeamService newFullTeamService() {
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
final OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor)
.build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(FullTeamService.HOST)
.client(client)
.addConverterFactory(GsonConverterFactory.create(GsonUtils.get()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit.create(FullTeamService.class);
}
}
and GsonUtils.java
is:
public class GsonUtils {
private static final Gson sGson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.registerTypeAdapter(NotificationObject.class, new NotificationDeserializer())
.create();
private GsonUtils() {}
public static Gson get() {
return sGson;
}
}
NotificationObject
is something like:
public class NotificationObject {
@SerializedName("ID")
@Expose
private long ID;
@SerializedName("type")
@Expose
private Type type;
@SerializedName("DataObject")
@Expose
private NotificationDataObject dataObject;
public void setDataObject(NotificationDataObject newsFields) {
dataObject = newsFields;
}
@SuppressWarnings("unchecked")
public <T> T getDataObject() {
return (T) dataObject;
}
public enum Type {
@SerializedName("0")
CHAT_MESSAGE,
@SerializedName("10")
GAME_APPLICATION,
@SerializedName("20")
GAME_APPLICATION_RESPONSE,
@SerializedName("30")
GAME_INVITE....
}
}
NotificationDataObject
as new class is like:
public class NotificationDataObject {}
and finally NotificationDeserializer
is like:
public class NotificationDeserializer implements JsonDeserializer<NotificationObject> {
@Override
public NotificationObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
final JsonObject itemBean = json.getAsJsonObject();
final NotificationObject object = GsonUtils.getSimpleGson().fromJson(itemBean, NotificationObject.class);
switch (object.getType()) {
case CHAT_MESSAGE:
break;
case GAME_APPLICATION:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
GameApplicationNotification.class));
break;
case GAME_APPLICATION_RESPONSE:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
GameApplicationResponseNotification.class));
break;
case GAME_INVITE:
object.setDataObject(GsonUtils.get().fromJson(itemBean.get("DataObject").getAsJsonObject(),
GameInviteNotification.class));
break;
}
return object;
}
}
Happy coding ...!
any query will be appreciated...