readValue and readTree in Jackson: when to use which?

前端 未结 2 1820
旧时难觅i
旧时难觅i 2021-02-02 09:35

I\'m just starting using the Jackson JSON library. Jackson is a very powerful library, but it has a terribly extensive API. A lot of things can be done in multiple ways. This ma

相关标签:
2条回答
  • 2021-02-02 10:23

    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.

    0 讨论(0)
  • 2021-02-02 10:29

    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.

    0 讨论(0)
提交回复
热议问题