Search code examples
javaandroidgsonretrofitpojo

Add two more values in POJO based on a value from the API while setting it - Retrofit2 & Gson converter


First of all I apologise if there is the answer to this already. But I am just not sure what to search for.

Now I have Retrofit2 set with my POJO model and everything works fine. But the API for certain nodes returns the unix timestamp format for a date. And I would like for it to be converted and set to two values (day of the week, and human readable date) while POJO is being set.

Is this even possible, and how?

POJO is something like:

public class Pojo {

    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("name")
    @Expose
    private String name;

    @SerializedName("date")
    @Expose
    private int unixDate;

    public int getId() {

        return id;
    }

    public void setId(int id) {

        this.id = id;
    }

    public String getName() {

        return name;
    }

   public void setName(String name) {

        this.name = name;
    }

    public int getUnixDate() {

        return unixDate;
    }

    public void setUnixDate(int unixDate) {

        // Tried the conversion and storing here but it of course won't work
        this.unixDate = unixDate;
   }
}

Is there a way to instruct Retrofit2 or Gson converter to add two more values (day of the week & date) to the POJO based on unix time stamp, but have everything else default as it is.

EDIT: Just to clear up. I know how to use ThreeTen Android Backport and convert unix to date and day. I just need a way to instruct Gson converter or Retrofit2 to use that logic.

Cheers


Solution

  • Add new fields in your POJO. Don't annotate them as exposed. When making the retrofit call, in the onResponse method, assign value to the custom fields. Something like this:

    call.enqueue(new Callback<List<Pojo>>() {
    
       public void onResponse(List<Pojo> list) {
           for (Pojo pojo : list) {
               pojo.setDayOfWeek();
               pojo.setDate();
           }
       }
    
    }