readValue and readTree in Jackson: when to use which?

readValue() can be used for any and all types, including JsonNode. readTree() only works for JsonNode (tree model); and is added for convenience.

Note that you NEVER want to use your first example: it is equivalent to writing out your node as JSON, then reading it back -- just cast it.


Read value can be used for your own java classes:

public class Foo {
   private int a;
   private String b;
   private double[] c;

   // getters/setters
}

String json = "{\"a\":2, \"b\":\"a string\", \"c\": [6.7, 6, 5.6, 8.0]}";
ObjectMapper mapper = new ObjectMapper();
Foo foo = mapper.readValue(json, Foo.class);

i.e. You may choose readTree when you do not know exact type of the Object, and readValue when you know the Object type for sure.

Tags:

Java

Json

Jackson