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

How to map XML Wrapper with same elements and other elements

我有一个 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 class。

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

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

如果我使用自动模式源生成(使用 jaxb2-maven-plugin),我会得到 class:

            @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"
}