我正在学习使用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;
}
}
当我尝试使用Jackson将类序列化为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>
答案 0 :(得分:1)
你有一个城市列表。杰克逊正在使用&#39; city&#39;列表本身和列表成员。如果您将本地名称更改为&#39; cities&#39;,您可能会更喜欢这些结果。
不幸的是,这不是正确的答案。相反,似乎提供了正确的答案https://stackoverflow.com/a/27144625/131433。