杰克逊绑定具有不同名称的对象列表 [英] Jackson bind List of objects with different name
本文介绍了杰克逊绑定具有不同名称的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有2个班级:
public class Catalog{
private List<Country> countries = new ArrayList<>();
public List<Country> getCountries() {
return countries;
}
public void setCountries(List<Country> countries) {
this.countries = countries;
}
}
第二个:
public class Country{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
我想要什么? 创建xml,但使用不同的名称
What I want ? Create the xml but with different names
<Catalogue>
<Countries>
<Country>
<name>RO</name>
</Country>
<Country>
<name>RO</name>
</Country>
</Countries>
</Catalogue>
我使用以下代码编写xml
I write the xml using:
Catalogue catalogue = new Catalogue();
Country country = new Country();
country.setName("RO");
catalogue.getCountries().add(country);
catalogue.getCountries().add(country);
String xml = xmlMapper.writeValueAsString(catalogue); // serializing
System.out.println("The xml is " + xml);
我该怎么做? 我在元素@JsonGetter和@JsonSetter上尝试了@JsonProperty,但我无法做到这一点.
How do I do this? I tried with @JsonProperty on element, @JsonGetter and @JsonSetter but I'm unable to do this.
当我添加这些注释时,它会执行类似的操作
When I add those annotations it does something like
<Countries>
<Countries>
<name>RO</name>
</Countries>
</Countries>
推荐答案
JacksonXmlProperty
和JacksonXmlElementWrapper
注释应该对您有用:
JacksonXmlProperty
and JacksonXmlElementWrapper
annotations should work for you:
@JacksonXmlRootElement(localName = "Catalogue")
class Catalog{
@JacksonXmlProperty(localName = "Country")
@JacksonXmlElementWrapper(localName = "Countries")
private List<Country> countries = new ArrayList<>();
//...
}
这篇关于杰克逊绑定具有不同名称的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文