could the POJO used for Gson reused for the class

2020-07-03 07:42发布

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)?

2条回答
疯言疯语
2楼-- · 2020-07-03 07:59

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;
    }
}
查看更多
祖国的老花朵
3楼-- · 2020-07-03 08:01

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.

查看更多
登录 后发表回答