【问题标题】:Serialize Object to XML with Jackson使用 Jackson 将对象序列化为 XML
【发布时间】:2018-01-27 07:11:53
【问题描述】:

我想将Object 转换为XML。我正在使用com.fasterxml.jackson.dataformat.xml.XmlMapper 将对象序列化为 xml

我使用javax.xml.bind.annotation.* 来注释类和变量。

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Transaction {
  @XmlAttribute(required = true, name = "ch-full-name")
  private String fullName;
  @XmlAttribute(required = true, name = "ch-address")
  private String address;
  @XmlAttribute(required = true, name = "ch-city")
  private String city;
  @XmlAttribute(required = true, name = "ch-zip")
  private String zipCode;
  @XmlAttribute(required = true, name = "ch-country")
  private String country;
  @XmlAttribute(required = true, name = "ch-phone")
  private String phone;
  @XmlAttribute(required = true, name = "ch-email")
  private String email;

  ...getters; & setters;
}

赋值和序列化:

Transaction tran = new Transaction();
tran.setFullName("full name");
tran.setAddress("address");
tran.setEmail("email");
tran.setCity("city");
tran.setCountry("country");
tran.setZipCode("zip");
tran.setPhone("phone");

XmlMapper mapper = new XmlMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String xml = "<?xml version='1.0' encoding='UTF-8'?>" +
      mapper.writeValueAsString(tran);

所以xml 返回如下内容:

<?xml version="1.0" encoding="UTF-8"?>
<Transaction>
  <fullName>full name</fullName>
  <address>address</address>
  <city>city</city>
  <zipCode>zip</zipCode>
  <country>country</country>
  <phone>phone</phone>
  <email>email</email>
</Transaction>

但实际上应该是这样的:

<?xml version="1.0" encoding="UTF-8"?>
<transaction>
  <ch-full-name>full name</ch-full-name>
  <ch-address>address</ch-address>
  <ch-city>city</ch-city>
  <ch-zip>zip</ch-zip>
  <ch-country>country</ch-country>
  <ch-phone>phone</ch-phone>
  <ch-email>email</ch-email>
</transaction>

是否有正确的方法来设置 xml 的属性名称?如何更改包括类名在内的名称(Transaction 名称应为 transaction)?

【问题讨论】:

    标签: java xml spring serialization jackson


    【解决方案1】:

    由于您使用的是 Jackson,因此您需要使用 @JsonProperty("name") 以便在序列化时为变量赋予不同的名称。它也是杰克逊的一部分。

    @JsonProperty("ch-full-name")
    private String fullName;
    @JsonProperty("ch-address")
    private String address;
    @JsonProperty("ch-city")
    private String city;
    @JsonProperty("ch-zip")
    private String zipCode;
    @JsonProperty("ch-country")
    private String country;
    @JsonProperty("ch-phone")
    private String phone;
    @JsonProperty("ch-email")
    private String email;
    

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 2017-09-10
      • 2013-01-20
      • 2021-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-23
      相关资源
      最近更新 更多