@XmlAccessorType(XmlAccessType.FIELD) 不与@XmlElement 映射

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

POST 调用使用的是 属性 变量名而不是 @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 调用:

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

问题是最终 JSON 被创建为 companyName 而不是 company_name

@XmlElement 更改 xml 请求的字段名称而不是 json, 如果要重命名 JSON 的变量,则应使用 @JsonProperty("Name")

For e.g:
public class Test {
  @JsonProperty("first_name")
  public String firstName;
  @JsonProperty("last_name")
  public String lastName; 
}

o/p 对于 json 将是

"Test":{
  "first_name":"Parameter-Name",
  "last_name":"Parameter-Value"
}

编组和取消编组 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();
    }