xml - Jackson:XML to Map with List deserialization

标签 xml serialization jackson

有没有办法使用 Jackson 将以下 xml 反序列化为包含项目列表的 map ?

<order>
    <number>12345678</number>
    <amount>100.10</amount>
    <items>
        <item>
            <itemId>123</itemId>
            <amount>100.0</amount>
            <itemName>Item Name1</itemName>
        </item>
        <item>
            <itemId>234</itemId>
            <amount>200.00</amount>
            <itemName>Item Name1</itemName>
        </item>
    </items>
</order>

我试过

XmlMapper mapper = new XmlMapper();
LinkedHashMap map = (LinkedHashMap)mapper.readValue(xml, Object.class);

得到如下 map 。列表中的第一项丢失。

{
    order={
        number=12345678,
        amount=100.1,
        items={
            item={
                amount=200.0,
                itemName=ItemName2,
                itemId=234
            }
        }
    }
}

最佳答案

这是一个已知的 jackson-dataformat-xml 错误,归档于 issue 205 .简而言之,XML 中的重复元素被当前的 UntypedObjectDeserializer 实现吞没了。幸运的是,该报告的作者 ( João Paulo Varandas ) 还提供了 a temporary fix in the form a custom UntypedObjectDeserializer implementation .下面我分享我对修复的解释:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

import javax.annotation.Nullable;
import java.io.IOException;
import java.util.*;

public enum JacksonDataformatXmlIssue205Fix {;

    public static void main(String[] args) throws IOException {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<items>\n" +
                "    <item><id>1</id></item>\n" +
                "    <item><id>2</id></item>\n" +
                "    <item><id>3</id></item>\n" +
                "</items>";
        SimpleModule module = new SimpleModule().addDeserializer(Object.class, Issue205FixedUntypedObjectDeserializer.getInstance());
        XmlMapper xmlMapper = (XmlMapper) new XmlMapper().registerModule(module);
        Object object = xmlMapper.readValue(xml, Object.class);
        System.out.println(object);     // {item=[{id=1}, {id=2}, {id=3}]}
    }

    @SuppressWarnings({ "deprecation", "serial" })
    public static class Issue205FixedUntypedObjectDeserializer extends UntypedObjectDeserializer {

        private static final Issue205FixedUntypedObjectDeserializer INSTANCE = new Issue205FixedUntypedObjectDeserializer();

        private Issue205FixedUntypedObjectDeserializer() {}

        public static Issue205FixedUntypedObjectDeserializer getInstance() {
            return INSTANCE;
        }

        @Override
        @SuppressWarnings({ "unchecked", "rawtypes" })
        protected Object mapObject(JsonParser parser, DeserializationContext context) throws IOException {

            // Read the first key.
            @Nullable String firstKey;
            JsonToken token = parser.getCurrentToken();
            if (token == JsonToken.START_OBJECT) {
                firstKey = parser.nextFieldName();
            } else if (token == JsonToken.FIELD_NAME) {
                firstKey = parser.getCurrentName();
            } else {
                if (token != JsonToken.END_OBJECT) {
                    throw context.mappingException(handledType(), parser.getCurrentToken());
                }
                return Collections.emptyMap();
            }

            // Populate entries.
            Map<String, Object> valueByKey = new LinkedHashMap<>();
            String nextKey = firstKey;
            do {

                // Read the next value.
                parser.nextToken();
                Object nextValue = deserialize(parser, context);

                // Key conflict? Combine existing and current entries into a list.
                if (valueByKey.containsKey(nextKey)) {
                    Object existingValue = valueByKey.get(nextKey);
                    if (existingValue instanceof List) {
                        List<Object> values = (List<Object>) existingValue;
                        values.add(nextValue);
                    } else {
                        List<Object> values = new ArrayList<>();
                        values.add(existingValue);
                        values.add(nextValue);
                        valueByKey.put(nextKey, values);
                    }
                }

                // New key? Put into the map.
                else {
                    valueByKey.put(nextKey, nextValue);
                }

            } while ((nextKey = parser.nextFieldName()) != null);

            // Ship back the collected entries.
            return valueByKey;

        }

    }

}

关于xml - Jackson:XML to Map with List deserialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13961843/

相关文章:

java - 用java序列化员工列表

java - 没有找到类 org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 的序列化程序,也没有发现创建 BeanSerializer 的属性

objective-c - 在 Cocoa 中解析 iTunes 库 XML

c# - 使用 C# 在特定节点之前插入 XML 节点

c# - File.Exists 返回 true 然后 filestream 抛出 FileNotFoundException 仅在控制台登录

java - 使用 Jackson 生成 JSON 时标记对象

java - Jackson 动态数据反序列化失败,

java - 如何比较xml文件中的节点?

ruby-on-rails - Rails 3 仅在更改时更新序列化属性

c# - 将多项选择元素从 XML 序列化为 C#