JAX-RS changes json serializer

I want to change my serializer to jackson, so I can change the 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 to debug JacksonConfig

, breakpoint comes to constructor but not getContext

method

+3


source to share


2 answers


According to the ISO8601DateFormat and ISO8601 source code, the useful class used by Jackson to manipulate ISO8601 dates, the output you see is the expected output.

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"));

      

0


source


@Aribeiro's comment looks ok. You just need to change the data format as per your requirement.

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>

      

0


source







All Articles