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

Viewed 89729

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?

4 Answers

More simple way by using Gson.

JSONObject jsonObject = //...

PojoObject objPojo = new Gson().fromJson(jsonObject.toString(), PojoObject.class);

This worked for me.

Related