readValue and readTree in Jackson: when to use which?

前端 未结 2 1821
旧时难觅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.

提交回复
热议问题