Rimantas Jacikevicius
Rimantas Jacikevicius

Reputation: 527

JAX-RS change json serializer

I want to change my serializer to jackson, so I could change timestamp format, i tried like this:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JacksonConfig
        implements ContextResolver<ObjectMapper> {

    private final ObjectMapper objectMapper;

    public JacksonConfig() {
        objectMapper = new ObjectMapper();
        objectMapper.setDateFormat(new ISO8601DateFormat());
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                false);
    }

    @Override
    public ObjectMapper getContext(Class<?> objectType) {
        return objectMapper;
    }
}

and in ApplicationConfig :

    resources.add(com.rfid.server.helpers.JacksonConfig.class);

It didn't work, I still get timestamps formatted like his: 2014-12-12T17:52:33.35031+02:00"

I tried debugging JacksonConfig, breakpoint comes to the constructor, but not getContext method

Upvotes: 3

Views: 762

Answers (2)

nnunes10
nnunes10

Reputation: 550

The @aribeiro comment seems to be ok. You just have to change the data format according to your requirements.

Make sure you have the following dependency in your project:

<dependency>
  <groupId>org.codehaus.jackson</groupId>
  <artifactId>jackson-jaxrs</artifactId>
  <version>1.9.13</version>
</dependency>

Upvotes: 0

Ant&#243;nio Ribeiro
Ant&#243;nio Ribeiro

Reputation: 4202

According to the source code of ISO8601DateFormat and to the ISO8601 utility class, used by Jackson to manipulate dates in the ISO8601 format, the result that you're seeing is the expected result.

If you want to have a new format for the date, you should do something like:

objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS"));

Upvotes: 1

Related Questions