有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用Jackson将JSON标量读取为singleelement double[]

假设我有以下两个JSON文件

{
  "a": [1, 2]
}

{
  "a": 1
}

我想使用Jackson将它们反序列化为以下形式的对象-

public class Foo {
    public double[] a;
}

因此,我将得到两个对象,Foo{a=[1,2]}Foo{a=[1]}。有没有可能说服Jackson将标量1反序列化为双数组[1],最好使用Jackson数据绑定api


共 (1) 个答案

  1. # 1 楼答案

    是的,你可以

    通过使用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;
    }
    

    输出

    [2.0]
    [3.0, 4.0, 5.0]
    

    快速注释

    关于杰克逊的版本。ACCEPT_SINGLE_VALUE_AS_ARRAY的文件说:

    Note that features that do not indicate version of inclusion were available in Jackson 2.0 (or earlier); only later additions indicate version of inclusion.

    该功能没有@sincejavadoc注释,因此它应该在Jackson的最新版本中工作