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

后端 未结 3 1314
死守一世寂寞
死守一世寂寞 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:26

    You can use @Embedded annotation for your related POJO which refers to another class.

    You can do like this:

    Article.java

    @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 // We need relation to Media table
        @Expose
        @SerializedName("media")
        public List media;
    }
    

    Media.java

    public class Media {
        @ColumnInfo (name = "media_id")
        public Long id;
    }
    

    So now on, you can directly use this POJO as Entity for ROOM.


    Please note:

    Though i'm not sure about how you'll handle that relation (because, Media obj is in list for Article class, you'll need to use type converter for that)

    Reference from here

提交回复
热议问题