Jackson XmlMaaper无法解码null Double。

huangapple go评论73阅读模式
英文:

Jackson XmlMaaper fails to decode null Double

问题

我遇到了一个奇怪的Jackson问题。XmlMapper无法反序列化自身序列化的内容。
而且只有在Double数组中有null时才会出现错误。下面是重现此问题的示例测试案例:

@Test
public void testDerSer(){
    Double[] testDouble = new Double[]{null, null, null, 3.0d, 34.5d};
    try {
        ObjectMapper xmlMapper = new XmlMapper();
        byte[] bytes = xmlMapper.writeValueAsBytes(testDouble);
        System.out.println(new String(bytes));
        Double[] doubles = xmlMapper.readValue(bytes, Double[].class);
        System.out.println(doubles);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

序列化的数据如下:

<Doubles><item/><item/><item/><item>3.0</item><item>34.5</item></Doubles>

错误信息为:

com.fasterxml.jackson.databind.exc.MismatchedInputException: 无法从START_OBJECT标记中反序列化`java.lang.Double`的实例
英文:

I’m experiencing a strange Jackson issue. The XmlMapper could not deserialize what is serialized by itself.
And the error only occurs when there’re nulls in the Double array. A sample test case to reproduce the issue is below:

@Test
public void testDerSer(){
    Double[] testDouble = new Double[]{null, null, null, 3.0d, 34.5d};
    try {
        ObjectMapper xmlMapper = new XmlMapper();
        byte[] bytes = xmlMapper.writeValueAsBytes(testDouble);
        System.out.println(new String(bytes));
        Double[] doubles = xmlMapper.readValue(bytes, Double[].class);
        System.out.println(doubles);
    }
    catch (IOException e) {
        e.printStackTrace();
    }
}

The serialized payload looks like this:

&lt;Doubles&gt;&lt;item/&gt;&lt;item/&gt;&lt;item/&gt;&lt;item&gt;3.0&lt;/item&gt;&lt;item&gt;34.5&lt;/item&gt;&lt;/Doubles&gt;

And the error is:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.lang.Double` out of START_OBJECT token

答案1

得分: 1

如果将Double[]替换为ArrayList,你会得到结果:

xmlMapper.readValue(bytes, ArrayList.class)

然后你会得到:

[{}, {}, {}, 3.0, 34.5]
英文:

If you replace Double[] with ArrayList you get result

xmlMapper.readValue(bytes, ArrayList.class)

then you get

[{}, {}, {}, 3.0, 34.5]

huangapple
  • 本文由 发表于 2020年10月1日 22:12:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64157217.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定