Reputation: 2643
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
Upvotes: 1
Views: 67
Reputation: 56
I interpreted your problem that you have issue while creating custom logic for date parsing in GSON. The problem is that this method doesn't instruct GSON and it uses it's own deserialization, so it uses that system setting. Just create your own class and implement JsonDeserializer interface.
public class DiyDateParser implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
Date date = new Date((long)timeStamp*1000);
//Your implementation for date parsing
try {
return formatter.parse(date);
} catch (ParseException e) {
System.err.println("Failed to parse Date due to:", e);
return null;
}
}
}
After this you can use it like that:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DiyDateParser());
Upvotes: 0
Reputation: 857
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();
}
}
}
Upvotes: 1