如何使用 Jackson 反序列化以下 json
我有以下 json:,
{
"id":"myid",
"fields":{
"body":"text body"
}
}
将其反序列化为以下 Java 类:
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;
}
我想使用 Jackson Json 反序列化器 。这不起作用,因为 body
字段嵌套在 fields
内部类中。
我无法更改 json 结构,因此有什么方法(可能使用注释)可以将 body
字段从 TestItem.fields.body
重新映射到 TestItem.body
?
编辑: 我应该说这是一个更大的类层次结构的一部分,练习的目的是减少它的深度。换句话说,我知道我可以声明一个内部类,然后访问它,但这不是我想要实现的目标。
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 depth 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几个功能请求(如果实现)将允许有限的一级包装/展开。但目前还没有声明性的方法来做到这一点。在某种程度上,这是边缘情况,因为这涉及数据转换而不是数据绑定(不幸的是,我想不出好的对象转换库,因此那里可能存在一些差距)。
那么,通常要做的是进行两阶段绑定:首先绑定到中间类型(通常是 java.util.Map 或 jackson JsonNode(树模型));修改它们,然后从该类型转换为实际结果。例如这样的事情:
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: