【发布时间】:2020-07-07 08:44:30
【问题描述】:
尝试将 JSON 反序列化/序列化为我创建的 Java bean。对杰克逊和这项努力来说真的很陌生,所以请多多包涵。我有以下内容:
{
"foo": {
"firstBlock": {
"myValue": 1,
"someBool": true,
"stringValue": "OK"
},
"anotherBlock": {
"values": [
{
"yikes01": 42
},
{
"yikes02": 215
}
],
"myInt": 64,
"logging": "Yes"
}
}
}
我的 Java bean 被分解成几个,因为 JSON 中的对象被重复使用,所以它是:
@JsonRootName("foo")
public class FooBean {
private FirstBlockBean firstBlock;
private AnotherBlockBean anotherBlock;
@JsonGetter("firstBlock")
public FirstBlockBean getFirstBlock() { return firstBlock; }
@JsonSetter("firstBlock")
public void setFirstBlock(FirstBlockBean firstBlock) { this.firstBlock = firstBlock; }
@JsonGetter("anotherBlock")
public AnotherBlockBean getAnotherBlock() { return anotherBlock; }
@JsonSetter("firstBlock")
public void setAnotherBlock(AnotherBlockBean anotherBlock) { this.anotherBlock = anotherBlock; }
}
@JsonRootName("firstBlock")
public class FirstBlockBean {
private int myValue;
private Boolean someBool;
private String stringValue;
@JsonGetter("myValue")
public int getMyValue() { return myValue; }
@JsonSetter("myValue")
public void setMyValue(int myValue) { this.myValue = myValue; }
@JsonGetter("someBool")
public Boolean getSomeBool() { return someBool; }
@JsonSetter("someBool")
public void setSomeBool(Boolean someBool) { this.someBool = someBool; }
@JsonGetter("stringValue")
public String getStringValue() { return stringValue; }
@JsonSetter("someBool")
public void setStringValue(String stringValue) { this.stringValue = stringValue; }
}
...和AnotherBlockBean 类以类似的方式实现(为简洁起见省略。)我为此使用Jackson,我的问题是-Jackson 中是否有一种机制可以针对这种情况进行序列化和反序列化?理想情况下,我想要一些类似的东西(下面的伪代码,因为我无法通过 Google 搜索或在此处搜索来显示任何内容):
// Assume "node" contains a JsonNode for the tree and foo is an uninitialized FooBean class object.
JsonHelper.deserialize(node, FooBean.class, foo);
此时我可以读回这些值:
int i = foo.getFirstBlock().getMyValue();
System.out.println("i = " + i); // i = 1
同样,我希望能够获取 foo 实例并使用另一种方法将其序列化回 JSON。我是梦想着想要这种内置功能还是它存在?
【问题讨论】:
标签: java json serialization jackson deserialization