Given the following data
{
"version" : 1,
"data" : [ [1,2,3], [4.5,6]]
}
I tried the following definitions and used ObjectMapper.readValue(jsonstring, Outer.class)
class Outer {
public int version;
public List<Inner> data
}
class Inner {
public List<Integer> intlist;
}
I got:
Can not deserialize instance of Inner out of START_ARRAY token"
In the Outer class, if I say
List<List<Integer> data;
then deserialization works.
But in my code, the Outer and Inner classes have some business logic related methods and I want to retain the class stucture.
I understand that the issue is that Jackson is unable to map the inner array to the 'Inner' class. Do I have to use the Tree Model in Jackson? Or is there someway I can still use the DataModel here ?
Jackson needs to know how to create an Inner
instance from an array of ints. The cleanest way is to declare a corresponding constructor and mark it with the @JsonCreator annotation.
Here is an example:
public class JacksonIntArray {
static final String JSON = "{ \"version\" : 1, \"data\" : [ [1,2,3], [4.5,6]] }";
static class Outer {
public int version;
public List<Inner> data;
@Override
public String toString() {
return "Outer{" +
"version=" + version +
", data=" + data +
'}';
}
}
static class Inner {
public List<Integer> intlist;
@JsonCreator
public Inner(final List<Integer> intlist) {
this.intlist = intlist;
}
@Override
public String toString() {
return "Inner{" +
"intlist=" + intlist +
'}';
}
}
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.readValue(JSON, Outer.class));
}
Output:
Outer{version=1, data=[Inner{intlist=[1, 2, 3]}, Inner{intlist=[4, 6]}]}
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