2012-08-30 106 views
0

我无法将这部分JSON转换为POJO。我使用的是杰克逊的配置是这样的:将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,但列表让我难倒了。

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

+1

http://stackoverflow.com/questions/9829403/deserialize-json-to-arraylistpojo-using-jackson – mre

回答

3

我认为你的问题与你的类定​​义。看起来你希望Tags类包含来自Json的原始文本,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; 
    } 
}; 

在这里我用一个列表来表示JSON数组的字段标识,我告诉杰克逊反序列化列表,标签类的内容。这是必需的,因为Jackson没有通用声明的运行时信息。你会为索引做同样的事情,即有一个带有JsonDeserialize注释的字段List<Integer> indices

+0

这工作,谢谢! –

+0

另外,我必须使这两个类都静态才能使其正常工作。这是什么让我这样:http://stackoverflow.com/questions/8526333/jackson-error-no-suitable-constructor –

+1

看起来不错。请注意,其中一个注释('@JsonDeserialize(contentAs =)')是多余的:不会伤害,但不是必需的(因为字段签名具有所有信息)。 – StaxMan