Search code examples
jsonxmlrestxml-parsingresttemplate

@XmlAccessorType(XmlAccessType.FIELD) not mapping with @XmlElement


POST call is using property variable names instead of @XmlElement(name)

DTO:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "balance",
    "companyName",
    ...

@XmlRootElement(name = "CustomerDTO", namespace = "")
public class CustomerDTO {

    @XmlElement(namespace = "", required = true)
    protected String balance;
    @XmlElement(name = "company_name", namespace = "", required = true)
    protected String companyName;

POST call:

HttpEntity<CustomerDTO> entity = new HttpEntity(customerDTO, headers);
String result = restTemplate.postForObject(URL, entity, String.class);

The problem is that final JSON is getting created as companyName instead of company_name


Solution

  • Marshall and un-marshall the DTO:

    private String marshallTOJSON(CustomerDTO customerDTO) throws JAXBException {
            System.setProperty("javax.xml.bind.context.factory", "org.eclipse.persistence.jaxb.JAXBContextFactory");
            JAXBContext context = JSONJAXBContext.newInstance(CustomerDTO.class);
            Marshaller marshaller = context.createMarshaller();
            JSONMarshaller jsonMarshaller = JSONJAXBContext.getJSONMarshaller(marshaller, context);
            jsonMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            StringWriter writer = new StringWriter();
            jsonMarshaller.marshallToJSON(customerDTO, writer);
            return writer.toString();
        }