我正在學習使用Jackson來序列化XML。我的課堂結構如下。使用Jackson將對象序列化爲XML
class City {
@JacksonXmlProperty(localName = "CityName")
String cityName;
public City(String cityName) {
this.cityName = cityName;
}
public String getcityName() {
return cityName;
}
public void setcity(String cityName) {
this.cityName = cityName;
}
}
@JacksonXmlRootElement(localName = "Person")
class Person {
@JacksonXmlProperty(localName = "name")
private String name;
@JacksonXmlProperty(localName = "age")
private String age;
@JacksonXmlProperty(localName = "city")
private List<City> city;
public Person() { }
Person(String name, String age, List<City> city) {
this.name = name;
this.age = age;
this.city = city;
}
public String getname() {
return name;
}
public String getage() {
return age;
}
public List<City> getcity() {
return city;
}
public void setname(String name) {
this.name = name;
}
public void setage(String age) {
this.age = age;
}
public void setcity(List<City> city) {
this.city = city;
}
}
當我試圖序列使用傑克遜一類爲XML,我得到兩個標籤爲<city>
public class App
{
public static void main(String[] args)
{
try {
XmlMapper xmlMapper2 = new XmlMapper();
Person p = new Person();
City c1 = new City("abc");
City c2 = new City("def");
City c3 = new City("ghi");
List<City> cityList = new ArrayList<City>();
cityList.add(c1);
cityList.add(c2);
cityList.add(c3);
p.setname("setattr");
p.setage("55");
p.setcity(cityList);
xmlMapper2.enable(SerializationFeature.INDENT_OUTPUT);
String respPerson = xmlMapper2.writeValueAsString(p);
System.out.println(respPerson);
} catch (Exception e) {
e.printStackTrace();
}
}
這是我得到的輸出。
<Person><name>setattr</name><age>55</age><city><city><CityName>sfo</CityName></city><city><CityName>sjc</CityName></city><city><CityName>sea</CityName></city></city></Person>
你能幫我理解爲什麼我會得到城市的兩個標籤,我該如何修復它?
我想輸出是這樣的,
<Person><name>setattr</name><age>55</age><city><CityName>sfo</CityName><CityName>sjc</CityName><CityName>sea</CityName></city></Person>
你能告訴我這是重複的嗎?我已經檢查過這個帖子。任何關於如何修復我的代碼以使其工作的建議? – Anit
使用@JacksonXmlElementWrapper(useWrapping = false),我仍然可以看到標籤被每個標籤包圍。相反,我只需要一個圍繞所有城市名稱的標記 –
Anit