gpt4 book ai didi

java - 如何使用相同元素和其他元素映射 XML Wrapper

转载 作者:太空宇宙 更新时间:2023-11-04 10:07:25 27 4
gpt4 key购买 nike

我有一个 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 Controller 的 Spring Boot 应用程序,它需要:

<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 boot 应用程序并使用上述 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"
}

关于java - 如何使用相同元素和其他元素映射 XML Wrapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52761291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com