javapenguin javapenguin - 2 months ago 24
Java Question

javax.ws.rs.core.Response.ResponseBuilder generate java.util.Date as number

I'm using javaee-api 6.0.

I have an entity bean with a java.util.Date field called updated.

public class Tariff implements Serializable {
private Date updated


And I have a REST service.

@GET
@Path("/example")
public Response getTariff() {
return Response.status(200).entity(new Records(createExampleTariff())).build();
}


When I call my REST service it returns the date as a number.

{"records":{"description":"OTHER","message":"Nothing to say","status":"OK", "updated":1475822878961},"status":"ok"}


Anyone know how I can work past this, without using a DTO.

Answer

Reason:

The date is always stored as the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

Solution:

You can convert the Date format using org.codehaus.jackson.map.JsonSerializer. by writing a class JsonDateSerializer with that conversion logic.

@JsonSerialize(using=JsonDateSerializer.class)
public Date getDate() {
   return date;
}

you can get detailed explanation here