Jackson将POJO转XML时移除List包装节点问题求助
解决Jackson XML序列化时列表包装标签无法移除的问题
问题原因
你的代码中存在两个核心问题导致@JacksonXmlElementWrapper(useWrapping = false)未生效:
- 非静态内部类的序列化限制:
Parent和Child作为非静态内部类,Jackson序列化时依赖外部Company实例,可能干扰注解的正常解析。 - 多态类型注解与列表包装的冲突:
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT)会给每个子类实例包裹一层类型名标签,此时Jackson会将列表的每个元素视为独立属性,用列表属性名childs作为外层标签包裹,覆盖了useWrapping = false的效果。
解决方案
修改代码如下,调整内部类类型并替换多态注解的实现方式:
@JacksonXmlRootElement(localName = "my_company") public class Company { public String comName; public String comEmail; @JacksonXmlElementWrapper(useWrapping = false) public List<Parent> childs; // 添加无参构造函数,Jackson序列化必须 public Company() {} Company(String comName, String comEmail, List<Parent> childs) { this.comName = comName; this.comEmail = comEmail; this.childs = childs; } // 改为静态内部类,让Jackson可独立序列化 static class Parent {} // 用@JacksonXmlRootElement直接指定XML标签名,替代原多态注解组合 @JacksonXmlRootElement(localName = "my_child") static class Child extends Parent { public String street; public String state; public String city; // 添加无参构造函数 public Child() {} Child(String street, String state, String city) { this.street = street; this.state = state; this.city = city; } } }
效果验证
修改后序列化生成的XML将符合你的需求:
<my_company> <comName>A</comName> <comEmail>ema</comEmail> <my_child> <street>a</street> <state>b</state> <city>c</city> </my_child> <my_child> <street>a</street> <state>b</state> <city>c</city> </my_child> </my_company>
扩展说明(若需保留多态支持)
如果需要支持多个Parent子类(如Child和AnotherChild),可以在Parent类上添加多态类型注解,同时调整类型信息的注入方式:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type") @JsonSubTypes({ @JsonSubTypes.Type(value = Child.class, name = "my_child"), @JsonSubTypes.Type(value = AnotherChild.class, name = "another_child") }) static class Parent {}
此时XML会在每个子节点中添加type属性标识类型,例如:
<my_child type="my_child"> <street>a</street> </my_child>
内容的提问来源于stack exchange,提问作者Estudio Tademan
相关产品推荐
相关产品推荐

