Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 467
lannyf Avatar asked Aug 16 '17 12:08

lannyf


2 Answers

It will work but may result in some issues in the future and is therefore not recommended for a clean software design. See this talk 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.

like image 89
G00fY Avatar answered Nov 10 '22 02:11

G00fY


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;
    }
}
like image 12
Android Team Avatar answered Nov 10 '22 02:11

Android Team