【发布时间】:2021-03-10 15:52:39
【问题描述】:
我必须创建一个 XSD,以便生成一个 POJO 以在代码中使用。(使用 jaxb2-maven-plugin)
该 pojo 将用于填充字段,然后被序列化为 XML 以发送到另一个服务。 (使用 XmlMapper)
我需要找到正确的方法来创建复杂对象的集合,以便生成的 XML 看起来像这样:
<Request>
<cars>
<car>
<name>golf</name>
<engine>1.6</engine>
<noOfSeats>5</noOfSeats>
</car>
<car>
<name>polo</name>
<engine>1.4</engine>
<noOfSeats>5</noOfSeats>
</car>
<car> ... </car>
</cars>
</Request>
我在这里和那里尝试了不同的解决方案,但我得到的结果如下:
错误 1
<Request>
<cars>
<car>
<car>...</car>
<car>...</car>
</car>
</cars>
</Request>
或
错误 2
<Request>
<cars>
<cars>...</cars>
<cars>...</cars>
</cars>
</Request>
似乎我无法获得包含根列表“汽车”和项目“汽车”的正确定义 并在名为汽车的 Car 的 pojo 列表中。
这是一个失败的场景,但最接近我的需要: XSD
<xs:element name="Request">
<xs:complexType>
<xs:sequence>
<xs:element name="cars" type="car" minOccurs="0" maxOccurs="unbounded" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="car">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
...
</xs:sequence>
</xs:complexType>
生成的 Request 类的列表为
List<Car> cars;
这是我所期望的,但在 Car 的定义中没有根名称标签。 所以在序列化为XML时会出现错误2的场景
这是我使用的映射器
XmlMapper.builder()
.addModule(new JaxbAnnotationModule())
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.build();
使用 Java 8、spring boot 2 和 maven
更新 我接受了下面的回复,因为它是正确的并且有效。 但我决定进行更新,因为我的主要问题实际上是序列化程序。 XmlMapper 没有序列化正确的方式或预期的方式。 我终于用下面的方法得到了正确的结果:
public Jaxb2Marshaller mashaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(Request.class);
return marshaller;
}
【问题讨论】:
标签: java xml collections xsd jaxb