Say I have the following two JSON files
{
"a": [1, 2]
}
and
{
"a": 1
}
I want to use Jackson to deserialize them both into an object of the following form -
public class Foo {
public double[] a;
}
so I would end up with two objects, Foo{a=[1,2]}
and Foo{a=[1]}
. Is it possible to persuade Jackson to deserialize a scalar 1
to a double array [1]
, preferably using the jackson-databind api?
Yes you can.
By using the ObjectMapper#.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
idiom.
Self-contained example here:
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;
}
Output
[2.0]
[3.0, 4.0, 5.0]
Quick note
About Jackson's version required. The docs for ACCEPT_SINGLE_VALUE_AS_ARRAY
say:
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.
The feature has no @since
javadoc annotation, so it should work in most recent-ish versions of Jackson.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With