如何从json树反序列化?

时间:2016-01-06 08:14:22

标签: java json jackson

假设我已经阅读了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);

   }
}

1 个答案:

答案 0 :(得分:5)

您只需使用treeToValue

MyClass myclass2 = mapper.treeToValue(tree, MyClass.class);

其中mapper是您的杰克逊映射器而tree是您的JsonNode