假设我已经读取了 json 树。
是否可以从中反序列化(不转换回字符串)?
public class TryDeserializeNode {
public static class MyClass {
private int x = 11, y = 12;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
MyClass myClass = new MyClass();
String string = mapper.writeValueAsString(myClass);
JsonNode tree = mapper.readTree(string);
// how to deserialize from tree directly?
// MyClass myclass2 = mapper.readValue(tree.toString(), MyClass.class);
MyClass myclass2 = mapper.readValue(tree, MyClass.class);
}
}
最佳答案
您可以简单地使用 treeToValue
:
MyClass myclass2 = mapper.treeToValue(tree, MyClass.class);
mapper
是您的 Jackson 映射器,tree
是您的 JsonNode
。
关于java - 如何从json树反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34628426/