JAX-RS @Produces: how to customize JSON? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of JAX-RS @Produces: how to customize JSON? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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:

public class EntitiesController {
    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?


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> {
    public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonGenerationException {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyy");
        String format = formatter.format(value);
We are here to answer your question about JAX-RS @Produces: how to customize JSON? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji