Jackson 绑定具有不同名称的对象列表 [英] Jackson bind List of objects with different name
本文介绍了Jackson 绑定具有不同名称的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有两个班级:
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<>();
//...
}
这篇关于Jackson 绑定具有不同名称的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文