2

There was a requirment formating java.util.Date into string rather than timestamp in json.

{
    "partyName": "Lifecare Pharmaceuticals",
    "partyShortName": null,
    "lastUpdateDate": 1486639814590, // replace with dd-mm-yyyy hh:mm:ss
}

To achive the date formatting I added the following ObjectMapperProvider

@Provider
@Component
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

   @Override
   public ObjectMapper getContext(Class<?> type) {
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.enable(SerializationConfig.Feature.USE_ANNOTATIONS);
      objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
      return objectMapper;
    }
}

The above solution worked but creates another issue ignoring XmlTransient annotation. In model classes Party has collection of PartyContacts and PartyContact mapped like

@Column(name = "PARTY_ID", referencedColumnName = "PARTY_ID", insertable = false, updatable = false)
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch =FetchType.LAZY)
private Party party;

and getter method

@XmlTransient
public Party getParty() {
    return party;
}

Here the XmlTransient annotation didnt work hence json loading recursively. I've seen onemore @JsonIgnore annotation but cant make it work with XmlTransient.

vels4j
  • 11,208
  • 5
  • 38
  • 63

1 Answers1

2

In Jackson 2.x it can be achieved with a proper AnnotationIntrospector.

Supporting both Jackson and JAXB annotations

To support both Jackson and JAXB annotations, you need a JacksonAnnotationIntrospector and a JaxbAnnotationIntrospector. Both introspectors can be combined with an AnnotationIntrospectorPair:

AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);

Supporting only JAXB annotations

If you want to support only JAXB annotations, register only the JaxbAnnotationIntrospector:

AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
mapper.setAnnotationIntrospector(introspector);

Dependency

To use the JaxbAnnotationIntrospector, the following dependency is required:

<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-jaxb-annotations</artifactId>
    <version>2.8.6</version>
</dependency>

For more details, have a look at the jackson-module-jaxb-annotations module documentation.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Perfect, works. I've one more question, rather than providing `new ObectMapper` cant we access existing objectMapper which Jersey uses default and attach the extra config? – vels4j Feb 13 '17 at 04:55
  • @vels4j There's no such thing as _existing `ObjectMapper`_. The serialisation and deserialization are handled by other Jackson APIs. – cassiomolin Feb 13 '17 at 08:03