开发者

How to deserialize the following json using Jackson

I have the following json:

{
  "id":"myid",
  "fields":{
    "body":"text body"
    }
}

which I want to deserialize into the following Java class:

class TestItem {
private String id;
private String body;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getBody() {
    return body;
}

public void setBody(String body) {
    this.body = body;
}

using the Jackson Json deserializer. This doesn't work because the body field is nested inside a fields inner class.

I can't change the json structure, so is there any way (perhaps using annotations) I can remap of the body field up from TestItem.fields.body to TestItem.body?

Edit: I should have said this is part of a larger class hierarchy and the aim of the excercise is to reduce the dep开发者_JAVA百科th of it. In other words, I know that I COULD declare an inner class and then access that, but that is not what I'm trying to achieve.


There are couple of feature requests that (if implemented) would allow limited one-level wrapping/unwrapping. But currently there is no declarative way to do this. And to some degree it is edge case, since this goes into data transformation as opposed to data binding (unfortunately I can't think of good object transformation libs, so there may be bit of gap there).

What is usually done, then, is to do two-phase binding: first into intermediate types (often java.util.Map, or jackson JsonNode (Tree model)); modify those, and then convert from this type to actual result. For example something like this:

JsonNode root = mapper.readTree(jsonSource);
// modify it appropriately (add, remove, move nodes)
MyBean bean = mapper.convertValue(root, MyBean.class);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜