0

我无法将这一点 JSON 放入 POJO。我正在使用这样配置的杰克逊:

protected ThreadLocal<ObjectMapper> jparser = new ThreadLocal<ObjectMapper>();

    public void receive(Object object) {
    try { 
        if (object instanceof String && ((String)object).length() != 0) {
            ObjectDefinition t = null ; 
            if (parserChoice==0) { 
                if (jparser.get()==null) {
                    jparser.set(new ObjectMapper());
                }
                t = jparser.get().readValue((String)object, ObjectDefinition.class);
            }

            Object key = t.getKey();
            if (key == null)
                return;
            transaction.put(key,t); 
        } 
    } catch (Exception e) { 
        e.printStackTrace();
    }
}

这是需要转换为 POJO 的 JSON:

{
    "id":"exampleID1",
    "entities":{
      "tags":[
         {
            "text":"textexample1",
            "indices":[
               2,
               14
            ]
         },
         {
            "text":"textexample2",
            "indices":[
               31,
               36
            ]
         },
         {
            "text":"textexample3",
            "indices":[
               37,
               43
            ]
         }
      ]
}

最后,这是我目前对 java 类的内容:

    protected Entities entities;
@JsonIgnoreProperties(ignoreUnknown = true)
protected class Entities {
    public Entities() {}
    protected Tags tags;
    @JsonIgnoreProperties(ignoreUnknown = true)
    protected class Tags {
        public Tags() {}

        protected String text;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    };

    public Tags getTags() {
        return tags;
    }
    public void setTags(Tags tags) {
        this.tags = tags;
    }
};
//Getters & Setters ...

我已经能够将更简单的对象转换为 POJO,但这个列表让我很困惑。

任何帮助表示赞赏。谢谢!

4

1 回答 1

4

我认为您的问题在于您的班级定义。您似乎希望Tags该类包含来自 Json 的原始文本,它是一个数组。我会做什么:

protected Entities entities;
@JsonIgnoreProperties(ignoreUnknown = true)
protected class Entities {
    public Entities() {}
    @JsonDeserialize(contentAs=Tag.class)
    protected List<Tag> tags;

    @JsonIgnoreProperties(ignoreUnknown = true)
    protected class Tag {
        public Tag() {}

        protected String text;

        public String getText() {
            return text;
        }

        public void setText(String text) {
            this.text = text;
        }
    };

    public Tags getTags() {
        return tags;
    }
    public void setTags(Tags tags) {
        this.tags = tags;
    }
};

在字段标签上,我使用 List 来表示 Json 数组,并告诉 Jackson 将该列表的内容反序列化为 Tag 类。这是必需的,因为 Jackson 没有泛型声明的运行时信息。你会对索引做同样的事情,即有一个List<Integer> indices带有 JsonDeserialize 注释的字段。

于 2012-08-30T17:03:13.183 回答