Java - Jackson嵌套数组 [英] Java - Jackson nested arrays

查看:118
本文介绍了Java - Jackson嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下数据

{
   "version" : 1,
   "data" : [ [1,2,3], [4.5,6]]
}

I尝试了以下定义并使用 ObjectMapper.readValue(jsonstring,Outer.class)

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;
}

我得到:

无法反序列化START_ARRAY令牌的内部实例

Can not deserialize instance of Inner out of START_ARRAY token"

在外类中,如果我说

List<List<Integer> data;

然后反序列化工作。

但在我的代码中,Outer和Inner类有一些与业务逻辑相关的方法,我想要保留课程结构。

But in my code, the Outer and Inner classes have some business logic related methods and I want to retain the class stucture.

我知道问题是Jackson无法将内部数组映射到'Inner'类。我是否必须使用树杰克逊的模特?或者在某种程度上我仍然可以在这里使用DataModel?

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 ?

推荐答案

杰克逊需要知道如何创建<来自int数组的code> Inner 实例。最简洁的方法是声明一个相应的构造函数并用 @JsonCreator注释。

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.

以下是一个示例:

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));
    }

输出:

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

这篇关于Java - Jackson嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆