使用Jackson读取JSON标量作为单元素double []

Chr*_*lor 6 java json jackson

假设我有以下两个JSON文件

{
  "a": [1, 2]
}
Run Code Online (Sandbox Code Playgroud)

{
  "a": 1
}
Run Code Online (Sandbox Code Playgroud)

我想用杰克逊将它们反序列化为以下形式的对象 -

public class Foo {
    public double[] a;
}
Run Code Online (Sandbox Code Playgroud)

所以我最终得到两个对象,Foo{a=[1,2]}并且Foo{a=[1]}.是否有可能说服杰克逊将标量反序列化为1双数组[1],最好使用jackson-databind api?

Men*_*ena 5

是的你可以.

通过使用ObjectMapper#.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);成语.

这里有一个独立的例子:

package test;

import java.util.Arrays;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main( String[] args ) throws Exception {
        ObjectMapper om = new ObjectMapper();
        // configuring as specified         
        om.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        // scalar example
        String json = "{\"foo\":2}";
        // array example
        String otherJson = "{\"foo\":[3,4,5]}";
        // de-serializing scalar and printing value
        Main m = om.readValue(json, Main.class);
        System.out.println(Arrays.toString(m.foo));
        // de-serializing array and printing value
        Main otherM = om.readValue(otherJson, Main.class);
        System.out.println(Arrays.toString(otherM.foo));
    }
    @JsonProperty(value="foo")
    protected double[] foo;
}
Run Code Online (Sandbox Code Playgroud)

产量

[2.0]
[3.0, 4.0, 5.0]
Run Code Online (Sandbox Code Playgroud)

快速说明

关于Jackson的版本要求.文档ACCEPT_SINGLE_VALUE_AS_ARRAY说:

请注意,Jackson 2.0(或更早版本)中提供了不表示包含版本的功能; 只有后来的添加才表明包含的版本.

该功能没有@sincejavadoc注释,因此它应该适用于Jackson的最新版本.