How to efficiently map a org.json.JSONObject to a POJO?

前端 未结 4 2163
清歌不尽
清歌不尽 2020-12-05 00:28

This question must have been asked before, but I couldn\'t find it.

I\'m using a 3rd party library to retrieve data in JSON format. The library offers the data to me

4条回答
  •  半阙折子戏
    2020-12-05 00:44

    Adding an answer to an old question, but...

    Jackson can bind to/from the org.json types. In general it can convert between any types that it can bind to, by effectively (although not actually) serializing to JSON and deserializing.

    If you have the JsonOrgModule registered, you can simply do the conversion straight from ObjectMapper:

    @Test
    public void convert_from_jsonobject() throws Exception {
        JSONObject obj = new JSONObject().put("value", 3.14);
        ObjectMapper mapper = new ObjectMapper().registerModule(new JsonOrgModule());
        PojoData data = mapper.convertValue(obj, PojoData.class);
        assertThat(data.value, equalTo(3.14));
    }
    
    @Test
    public void convert_to_jsonobject() throws Exception {
        PojoData data = new PojoData();
        data.value = 3.14;
        ObjectMapper mapper = new ObjectMapper().registerModule(new JsonOrgModule());
        JSONObject obj = mapper.convertValue(data, JSONObject.class);
        assertThat(obj.getDouble("value"), equalTo(3.14));
    }
    
    public static final class PojoData {
        public double value;
    }
    

    I mentioned that this is effectively serialising? That's true, it serializes the input object into a TokenBuffer, which represents a stream of JSON parsing events, but with less impact of building strings etc., as it can largely reference data from the input. It then feeds this stream to a deserializer to produce the output object.

    So, it's somewhat similar to the suggestion to convert the JSONObject to a JsonNode, but much more general. Whether it's actually more efficient or not would need measuring: either you construct a JsonNode as an intermediate or a TokenBuffer, neither way is without overhead.

提交回复
热议问题