could the POJO used for Gson reused for the class used with Room

若如初见. 提交于 2020-03-18 04:00:07

问题


when using Gson it has POJO created for parsing/serializing the json data result from the remote service. It may have some Gson's annotation

public class User {
    @SerializedName(“_id”)
    @Expose
    public String id;
    @SerializedName(“_name”)
    @Expose
    public String name;
    @SerializedName(“_lastName”)
    @Expose
    public String lastName;

    @SerializedName(“_age”)
    @Expose
    public Integer age;
}

but for the class using with Room, it may have its own annotation:

import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;

@Entity
public class User {
    public @PrimaryKey String id;
    public String name;
    public String lastName;
    public int age;
}

could these two be combined into one with all of the annotation from two libs (if there is annotation clash (hope not), it would have to be resolved with long package names)?


回答1:


yes you can make one single pojo class for room and gson. and when request to server and if any data not be send in server that time used transient keyword and if you want not insert any field table used @Ignore.

used below code for gson and room..

 @Entity
public class User {

    @PrimaryKey(autoGenerate = true)
    @SerializedName("_id")
    @ColumnInfo(name = "user_id")
    public long userId;
    @SerializedName("_fName")
    @ColumnInfo(name = "first_name")
    private String name;

    public long getUserId() {
        return userId;
    }

    public void setUserId(long userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}



回答2:


It will work but may result in some issues in the future and is therefore not recommended for a clean software design. See this speech about it: Marko Miloš: Clean architecture on Android

As pointed out you should use different entities for your db and webresults/json and transform between them.



来源:https://stackoverflow.com/questions/45713643/could-the-pojo-used-for-gson-reused-for-the-class-used-with-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!