I’m having trouble getting this bit of JSON into a POJO. I’m using Jackson configured like this:
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();
}
}
Here’s the JSON that needs to be turned into a POJO:
{
"id":"exampleID1",
"entities":{
"tags":[
{
"text":"textexample1",
"indices":[
2,
14
]
},
{
"text":"textexample2",
"indices":[
31,
36
]
},
{
"text":"textexample3",
"indices":[
37,
43
]
}
]
}
And lastly, here’s what I currently have for the java class:
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 ...
I’ve been able to translate the more simple objects into a POJO, but the list has me stumped.
Any help is appreciated. Thanks!
I think your issue is with your class definition. It seems that you wish that the
Tagsclass contains the raw text from Json, which is an array. What I would do instead:Here on the field tags I use a List to represent the Json array, and I tell Jackson to deserialize the content of that list as the Tag class. This is required because Jackson doesn’t have the runtime information of the generic declaration. You’d do the same thing for the indices, namely have a field
List<Integer> indiceswith the JsonDeserialize annotation.