Android Room: Efficient way to transform json result into db object

后端 未结 3 1313
死守一世寂寞
死守一世寂寞 2021-02-19 19:35

Problem

I have a POJO parsed from an API call which looks like this

public class Article {

  public Long id;

  @Expose
  @Serialized         


        
3条回答
  •  南方客
    南方客 (楼主)
    2021-02-19 20:28

    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;
    }
    

提交回复
热议问题