Jackson ignoring XmlElement name/case when marshalling JSON Jackson ignoring XmlElement name/case when marshalling JSON json json

Jackson ignoring XmlElement name/case when marshalling JSON


JAXB annotations are not by default supported. You need to add the jackson-module-jaxb-annotations module and then register that with the ObjectMapper.

ObjectMapper mapper = new ObjectMapper();mapper.registerModule(new JaxbAnnotationModule());


As mentioned in a comment, add @JsonProperty to the fields.

It works fine for me, using Jackson 2.7.0:

@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "", propOrder = { "trackRequest" })@XmlRootElement(name = "Request")class Request {    @XmlElement(name = "TrackRequest")    @JsonProperty("TrackRequest")    private TrackRequest trackRequest;    public Request() {    }    public Request(TrackRequest trackRequest) {        this.trackRequest = trackRequest;    }}
@XmlAccessorType(XmlAccessType.FIELD)@XmlType(name = "", propOrder = { "inquiryNumber" })class TrackRequest {    @XmlElement(name = "InquiryNumber")    @JsonProperty("InquiryNumber")    private String inquiryNumber;    public TrackRequest() {    }    public TrackRequest(String inquiryNumber) {        this.inquiryNumber = inquiryNumber;    }}

Test

Request upsRequest = new Request(new TrackRequest("1Z12345E6205277936"));
Marshaller marshaller = JAXBContext.newInstance(Request.class).createMarshaller();marshaller.setProperty("jaxb.formatted.output", Boolean.TRUE);marshaller.marshal(upsRequest, System.out);
ObjectMapper mapper = new ObjectMapper();mapper.enable(SerializationFeature.INDENT_OUTPUT);mapper.writeValue(System.out, upsRequest);

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Request>    <TrackRequest>        <InquiryNumber>1Z12345E6205277936</InquiryNumber>    </TrackRequest></Request>
{  "TrackRequest" : {    "InquiryNumber" : "1Z12345E6205277936"  }}

Both XML and JSON output is using PascalCase.


To use this functionality to read the @JsonProperty and the XmlElement in spring-boot and its Jackson2ObjectMapperBuilder, you easily create a Bean to get the Builder everytime you need.

@Beanpublic Jackson2ObjectMapperBuilder jacksonBuilder() {    Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();    //configure features for serialization and deserialization    return builder;}

You can now autowire the builder and configure the ObjectMapper directly there where you need it:

@Componentpublic class MyClass {    private ObjectMapper objectMapper;    public MyClass(Jackson2ObjectMapperBuilder jacksonBuilder) {        super();        objectMapper = jacksonBuilder.build().registerModule(new JaxbAnnotationModule());    }    public String serialize(){        AnyObject ao = new AnyObject();        String json = objectMapper.writeValueAsString(ao);        return json;    }}