20

Jackson を使用して、次の xml をアイテムのリストを保持するマップに逆シリアル化する方法はありますか?

<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);

そして、次のマップを取得しました。リストの最初の項目がありません。

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

3 に答える 3

7

これはissue 205で報告されている既知のjackson-dataformat-xmlバグです。簡単に言えば、XML 内の重複した要素は、現在の実装によって飲み込まれます。幸いなことに、レポートの作成者 ( João Paulo Varandas ) もカスタム実装という形で一時的な修正を提供しました。以下に、修正の解釈を共有します。UntypedObjectDeserializerUntypedObjectDeserializer

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;

        }

    }

}
于 2018-09-14T18:57:01.187 に答える
1

readTree()andを使用する必要がある場合、他の答えは機能しませんJsonNode。それが醜い解決策であることは知っていますが、少なくともプロジェクトに誰かの要点を貼り付ける必要はありません。

プロジェクトの依存関係に org.json を追加します。

そして、次の操作を行います。

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.JSONObject;
import org.json.XML;
...
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
...
    JSONObject soapDatainJsonObject = XML.toJSONObject(data);
    return OBJECT_MAPPER.readTree(soapDatainJsonObject.toString());

変換は次のようになります。

XML -> JSONObject (org.json を使用) -> 文字列 -> JsonNode (readTree を使用)

もちろん、toJSONObject は重複を問題なく処理しreadTree()ます。可能であれば、Jackson の使用を避けることをお勧めします。

于 2019-08-11T15:20:06.060 に答える
-1

UntypedObjectDeserializer を拡張してこのジョブを実行することにより、カスタム デシリアライザーを作成しました。

于 2012-12-25T21:36:53.983 に答える