使用CXF XJC与JAXB绑定实现List<String>返回null而非空列表
解决CXF XJC生成List返回空列表而非null的问题
问题背景
使用CXF XJC 4.0插件将Schema转换为Java类时,SomeObject中定义的MyList(对应SomeType字符串类型,minOccurs="0")被生成为List<String>类型,但默认返回空列表而非null。序列化这类空列表时会生成不符合Schema要求的空标签,且无法修改原始Schema及生成的Java类,尝试过的JAXB绑定方案要么导致属性类型变为List<List>,要么适配器无法正常工作。
可行解决方案
1. 编写自定义XmlAdapter
创建适配器处理List<String>的序列化逻辑:空列表时返回null,避免生成无效XML标签;反序列化保持原有逻辑即可。
package com.example; import jakarta.xml.bind.annotation.adapters.XmlAdapter; import java.util.List; public class NullIfEmptyListAdapter extends XmlAdapter<List<String>, List<String>> { @Override public List<String> unmarshal(List<String> input) throws Exception { return input; } @Override public List<String> marshal(List<String> input) throws Exception { // 空列表或null时返回null,序列化时不会生成对应XML标签 return (input == null || input.isEmpty()) ? null : input; } }
2. 修改JAXB绑定文件
放弃使用<jxb:javaType>(该配置针对单个元素类型转换,会导致集合类型嵌套),直接在属性上指定适配器:
<jxb:bindings version="3.0" xmlns:jxb="http://jakarta.ee/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <jxb:bindings schemaLocation="my-schema.xsd" node="/xs:schema/xs:complexType[@name='SomeObject']/xs:sequence/xs:element[@name='MyList']"> <jxb:property> <jxb:adapter value="com.example.NullIfEmptyListAdapter"/> </jxb:property> </jxb:bindings> </jxb:bindings>
方案说明
- 此绑定会在生成的
SomeObject类的MyList属性上自动添加@XmlJavaTypeAdapter(NullIfEmptyListAdapter.class)注解,属性类型依然保持List<String>,不会出现类型嵌套问题。 - 序列化时,适配器会判断列表是否为空,为空则返回null,从而不生成对应的
<MyList>标签,完全符合Schema中minOccurs="0"的要求。
内容的提问来源于stack exchange,提问作者Lauro182
相关产品推荐
相关产品推荐

