Suzan Cioc
Suzan Cioc

Reputation: 30097

How to deserialize from json tree?

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

   }
}

Upvotes: 7

Views: 271

Answers (1)

Marcinek
Marcinek

Reputation: 2117

You could simply use treeToValue:

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

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

Upvotes: 5

Related Questions