I'm using a 3rd party library to retrieve data in JSON format. The library offers the data to me as a org.json.JSONObject. I want to map this JSONObject to a POJO (Plain Old Java Object) for simpler access/code.
For mapping, I currently use the ObjectMapper from the Jackson library in this way:
JSONObject jsonObject = //...
ObjectMapper mapper = new ObjectMapper();
MyPojoClass myPojo = mapper.readValue(jsonObject.toString(), MyPojoClass.class);
To my understanding, the above code can be optimized significantly, because currently the data in the JSONObject, which is already parsed, is again fed into a serialization-deserialization chain with the JSONObject.toString() method and then to the ObjectMapper.
I want to avoid these two conversions (toString() and parsing). Is there a way to use the JSONObject to map its data directly to a POJO?
Since you have an abstract representation of some JSON data (an
org.json.JSONObjectobject) and you're planning to use the Jackson library - that has its own abstract representation of JSON data (com.fasterxml.jackson.databind.JsonNode) - then a conversion from one representation to the other would save you from the parse-serialize-parse process. So, instead of using thereadValuemethod that accepts aString, you'd use this version that accepts aJsonParser:JSON is a very simple format, so it should not be hard to create the
convertJsonFormatby hand. Here's my attempt:Note that, while the Jackson's
JsonNodecan represent some extra types (such asBigInteger,Decimal, etc) they are not necessary since the code above covers everything thatJSONObjectcan represent.