使用Jackson

时间:2017-08-18 14:41:40

标签: java xml spring serialization jackson

我想将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)?

1 个答案:

答案 0 :(得分: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;