[英]Java - Jackson nested arrays
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)
我尝试了以下定义并使用了
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"
无法使用START_ARRAY令牌反序列化内部实例”
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. 但是在我的代码中,Outer和Inner类具有一些与业务逻辑相关的方法,我想保留该类的结构。
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 ?
还是有某种方式我仍然可以在这里使用DataModel?
Jackson needs to know how to create an Inner
instance from an array of ints. 杰克逊需要知道如何从一个整数数组创建一个
Inner
实例。 The cleanest way is to declare a corresponding constructor and mark it with the @JsonCreator annotation. 最干净的方法是声明一个对应的构造函数,并使用@JsonCreator批注对其进行标记。
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]}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.