Eniss Eniss - 1 month ago 14
Java Question

Serialize Object to XML with Jackson

I want to convert

Object
to
XML
. I am using
com.fasterxml.jackson.dataformat.xml.XmlMapper
to serialize the object to xml

I used
javax.xml.bind.annotation.*
to annotate the class and variables.

@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;
}


Assigning values and serializing:

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);


So
xml
returns something like this:

<?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>


But it actually is supposed to be like this:

<?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>


Is there a correct way to set attribute names for xml? How can I change names including class name(
Transaction
name should be
transaction
)?

Answer Source

Since you are using Jackson, you need to use @JsonProperty("name") in order to give different names to variables while serializing. It is also a part of Jackson.

@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;