1

I have a field that I want formatted differently when using XML and JSON, though Jackson only reads the JAXB annotation @XMLElement but ignores the Jackson annotation @JsonProperty when serializing to JSON.

@XmlElementWrapper(name = "ParticipantBindings")
@XmlElement(name = "ParticipantBinding")
@com.fasterxml.jackson.annotation.JsonProperty("participantBindings") // This is ignored?
public List<ParticipantBinding> getParticipantBindings() {
    return participantBindings;
}

My Spring boot controller is called as so

@GetMapping(path = "/{id}", produces = {MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<Participant> getParticipantById(@PathVariable("id") int id) {
    Participant p = participantDao.getParticipantFull(id);

    if (p == null) {
        throw new ResourceNotFoundException();
    } else {
        return ResponseEntity.ok(p);
    }
}

Where the expected result for sending a getrequest with accept-header: application/xml would be:

<ParticipantBindings>
   <ParticipanBinding>...</ParticipantBinding>
   <ParticipanBinding>...</ParticipantBinding>
<ParticipantBindings>

Where for application/json the expected result should be:

"participantBindings": [ ...]

And although XML is correctly formatted, the JSON is outputted as follows:

"ParticipantBinding" : [ ...]
Asger Weirsøe
  • 350
  • 1
  • 11

2 Answers2

0

The @XmlElement(name = "ParticipantBinding") annotation might be interfering with the @com.fasterxml.jackson.annotation.JsonProperty("participantBindings") annotation. Could you verify that your ObjectMapper bean has registered the module JaxbAnnotationModule at runtime by any chance?

You can check this by @Autowire-ing the ObjectMapper in any class and debugging the ObjectMapper when a method in the class is called. Evaluate mapper.getRegisteredModuleIds() to see which modules are registered.

If the ObjectMapper has indeed registered the module (which I'm guessing it has, as you might also be using it to serialize the object to XML), you might want register separate MessageConverters (each having a separate ObjectMapper) for separate media types. An example can be found here.

Michiel
  • 2,914
  • 1
  • 18
  • 27
0

If you come across this problem: The Jaxb message converter should be justed to serialize xml requests but is added only if JAXB2 is present on the classpath and if jackson xml is not.

Milgo
  • 2,617
  • 4
  • 22
  • 37