如何将 XML 包装器与相同的元素和其他元素映射



我有一个XML模式,元素name

<xsd:element name="name">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="given" maxOccurs="unbounded" type="xsd:string"/>
<xsd:element name="family" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

我需要将其映射到工作 java 类。

我有一个带有 JAXB XML 控制器的 Spring 引导应用程序,它需要:

<name>
<given>First</given>
<given>Second</given>
<family>Lastname</family>
</name>

如果我使用自动模式源代码生成(使用 jaxb2-maven-plugin(,我会得到一个类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"given",
"family"
})
public static class Name {
@XmlElement(required = true)
protected List<String> given = new ArrayList<>();
@XmlElement(required = true)
protected String family;
public List<String> getGiven() {
if (given == null) {
given = new ArrayList<>();
}
return this.given;
}
public void setGiven(List<String> given) {
this.given = given;
}
public String getFamily() {
return family;
}
public void setFamily(String value) {
this.family = value;
}
}

但问题是,当我运行 spring 启动应用程序并使用上述 XML 调用它时,出现错误:

*....Name["given"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token*

我无法控制发送数据的格式,因此无法更改接收的 XML。 我已经尝试了许多不同的解决方案,但完全坚持这一点。你能帮忙吗?

尝试使用@JacksonXmlElementWrapper(useWrapping = false)

@Test
public void test2() throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new XmlMapper();
Name name = mapper.readValue("<name>n" + "  <given>First</given>n" + "  <given>Second</given>n"
+ "  <family>Lastname</family>n" + "</name>", Name.class);
System.out.println(toString(name));
}
public static class Name {
@JacksonXmlElementWrapper(useWrapping = false)
public List<String> given = new ArrayList<>();
@XmlElement(required = true)
public String family;
}
public String toString(Object obj) {
try {
StringWriter w = new StringWriter();
new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true).writeValue(w, obj);
return w.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}

指纹

{
"given" : [ "First", "Second" ],
"family" : "Lastname"
}

最新更新