I'm migrating to Retrofit from Asynctask + Loader for our core networking. It was going well till I encountered ClassCastExceptions where they previously didn't occur:
ImagePojo imagePojo = (ImagePojo) mediaPojo; // Error: cannot cast MediaPojo to ImagePojo
Here's the skeleton of my POJOs in the hierarchy:
Parent/Generic media object
public class MediaPojo extends CustomObservable implements Parcelable {
@SerializedName("media_id")
private String mMid;
@SerializedName("type")
private String mType;
@SerializedName("title")
public MediaPojo() {
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mNid);
dest.writeString(mType);
dest.writeString(mTitle);
}
public static final Parcelable.Creator<MediaPojo> CREATOR = new Parcelable.Creator<MediaPojo>() {
@Override
public MediaPojo createFromParcel(Parcel source) {
return new MediaPojo(source);
}
@Override
public MediaPojo[] newArray(int size) {
return new MediaPojo[size];
}
};
...
}
// defines fields common to all media types
Video media type
public class VideoPojo extends MediaPojo implements Parcelable {
@SerializedName("video_id")
private String mVid;
@SerializedName("video_url")
private String mVideoUrl;
@SerializedName("thumbnail")
private String mThumbnail ...
}
Image media type POJO
public class ImagePojo extends MediaPojo implements Parcelable {
@SerializedName("image_url")
private String mImageUrl;
@SerializedName("width")
private String mImageWidth;
@SerializedName("height")
private String mImageHeight
...
}
// Other types: TextPojo, InfoGraphicPojo ...
So far, the only change I made to the POJOs in the migration was to add the @SerializedName annotations to allow Retrofit to automatically map the JSON fields to defined POJO instance variables. I find it necessary to do the generic MediaPojo to specific type POJO conversions at runtime as my REST calls to api.mydomain.com/media can return JSON representing media of various types (video, image, etc).
Is there any way to make Retrofit work around my already existing object inheritance structure? Or could it the way I do serialization with the Parcelable interface?