Using Spring RestControllers with Jackson JSON parsing, with AngularJS on the front side. I'm looking for an effective way for Jackson to serialize Instant as an era of milliseconds for later convenient use with JavaScript code. (On the browser side, I want to pass the ms era through Angular Date Filter : {{myInstantVal | date:'short' }}for my desired date format.)
On the Java side, the recipient that Jackson uses is simple:
public Instant getMyInstantVal() { return myInstantVal; }
Serialization will not work as is, because jackson-datatype-jsr310 does not return the default Epoch milliseconds for Instant. I looked at adding @JsonFormat to the above user to convert Instant to something that can use the front-end, but it suffers from two problems: (1) the template that I can provide is apparently limited to SimpleDateFormat, which does not provide the "epoch milliseconds" parameter, and (2) when I tried to send Instant as a formatted date to the browser instead, Jackson throws an exception because the @JsonFormat annotation requires the TimeZone attribute for the instances, which I don’t want to hardcode since it will differ from user to to the user.
My solution so far (and it works fine) is to create a replacement getter using @JsonGetter , which forces Jackson to use this method instead of for serialization myInstantVal:
@JsonGetter("myInstantVal")
public long getMyInstantValEpoch() {
return myInstantVal.toEpochMilli();
}
Is this the right way to do this? Or is there a nice annotation that I'm missing so I can use getMyInstantVal (), so I won’t need to create these additional methods?
source
share