I have a POJO parsed from an API call which looks like this
public class Article {
public Long id;
@Expose
@Serialized
All you have to do is use @Embedded
annotation for your POJO(Model Class) which will refer to another class. then create a type converter class.
@Embedded(prefix = "media")
private Meida media;
@TypeConverters({TypeConvertorClass.class})
@Database(entities = {Article .class,Media.class}, version = 1, exportSchema = false)
public abstract class `DataBaseExample` extends RoomDatabase {
}
public class Converters {
@TypeConverter
public static ArrayList fromString(String value) {
Type listType = new TypeToken>() {}.getType();
return new Gson().fromJson(value, listType);
}
@TypeConverter
public static String fromArrayLisr(ArrayList list) {
Gson gson = new Gson();
String json = gson.toJson(list);
return json;
}
}
public class TypeConvertorClass {
@TypeConverter
public static Media getMedia(String longId) {
return longId== null ? null : new Meida();
}
}
@Entity(tableName = "Article")
public class Article {
@ColumnInfo (name = "article_id")
public Long id;
@Expose
@SerializedName("section")
public String section;
@Expose
@SerializedName("title")
public String title;
@Expose
@SerializedName("topics")
public List topics;
@Embedded(prefix = "media") // We need relation to Media table
@Expose
@SerializedName("media")
public List media;
}
public class Media {
@ColumnInfo (name = "media_id")
public Long id;
}