Java - arrays built into Jackson

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:

Unable to deserialize Inner instance from 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 save the class.

I understand that the problem is that Jackson cannot map the internal array to the Internal class. Should I use a tree model in Jackson? Or can I still use the DataModel here?

+5
source share
1 answer

Jackson needs to know how to create an Inner instance from an int array. The cleanest way is to declare the appropriate 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)); } 

Conclusion:

 Outer{version=1, data=[Inner{intlist=[1, 2, 3]}, Inner{intlist=[4, 6]}]} 
+4
source

Source: https://habr.com/ru/post/1208482/


All Articles