JAX-RS @Produces: how to customize JSON?

I am new to JAX-RS and I want to serve my list of items as JSON. My entity model is something like this:

public class Entity {
    private String name;
    private Date date;
    private Float number;
}

This is how I am invoking the service:

@Path("/entities")
public class EntitiesController {
    @GET
    @Produces({"application/json"})
    public List<Entity> getEntities() {
        return EntityDAO.entitiesList();
    }
}

However, the date is not formatted but is displayed as a long.

This answer shows how to format a date using a JsonSerializer. If I extend JsonSerializer, then where do I put that subclass in my project?

Answer

I figured a solution myself:

Under a new serializers package I created the CustomJsonDateSerializer class, which will be delegated the responsibility of formatting the date attribute thanks to the @JsonSerialize(...) annotation.

So I modified my Entity class adding that annotation ontop of the field:

@JsonSerialize(using = CustomJsonDateSerializer.class)
private Date date;

And this is the content of CustomJsonDateSerializer:

package serializers;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class CustomJsonDateSerializer extends JsonSerializer<Date> {
    @Override
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonGenerationException {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyy");
        String format = formatter.format(value);
        jgen.writeString(format);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *