Jackson XML - 是否有 Java 内置类型可用于反序列化包含数组的对象?

Jackson XML - Is there a Java built-in type that can be used to deserialize an object containing arrays?

假设我的 XML 是:

<someObject>
  <someArray>
    <element>111</element>
    <element>222</element>
  </someArray>
</someObject>

是否有 Java 内置类型可用于反序列化此 XML 而无需自定义反序列化代码?

比如我用了一个Map<Object, Object>,只保留了一个element,另一个被覆盖了! :

String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
Map<Object, Object> resultObj = getXmlMapper().readValue(xmlStr, new TypeReference<Map<Object, Object>>(){});
System.out.println(resultObj);

这将打印:

{someArray={element=222}}

是否有 Jackson 可以理解并且可以正确处理数组的类型?

在您的具体情况下,您可以使用

new TypeReference<Map<Object, List>> 

输出:{someArray=[111, 222]}.

如果您的 XML 更复杂,我更愿意使用适当的结构。

@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
    @JacksonXmlProperty(localName = "someArray")
    List<String> someArray; 

    @Override
    // for testing
    public String toString() {
        return someArray.toString();
    }
}

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper map = new XmlMapper();
    String xmlStr = "<someObject><someArray><element>111</element><element>222</element></someArray></someObject>";
    SomeObject resultObj = map.readValue(xmlStr, new TypeReference<SomeObject>(){});
    System.out.println(resultObj);      
}

输出

[111, 222]

或者使用数组

@JacksonXmlRootElement(localName = "someObject")
public static class SomeObject {
    @JacksonXmlProperty(localName = "someArray")
    String[] someArray; 

    @Override
    public String toString() {
        return Arrays.asList(someArray).toString();
    }
}