Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize from json tree?

Tags:

java

json

jackson

Suppose I have json tree already read.

Is it possible to deserialize from it (without converting back to string)?

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);

   }
}
like image 921
Suzan Cioc Avatar asked Jan 06 '16 08:01

Suzan Cioc


1 Answers

You could simply use treeToValue:

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

where mapper is your Jackson mapper and tree is your JsonNode.

like image 82
Marcinek Avatar answered Oct 10 '22 03:10

Marcinek