Search code examples
javajsonserializationgson

How can I convert a JSONObject to a gson.JsonObject?


I have a org.json.JSONObject object.

What's the easiest way to create a gson.JsonObject object from it?

Thanks


Solution

  • The easiest way is to serialize your JSONObject to a json string using toString(), then parsing that json string into a JsonObject:

        org.json.JSONObject object = <your defined object>;
        JsonParser jsonParser = new JsonParser();
        JsonObject gsonObject = (JsonObject)jsonParser.parse(object.toString());
    

    Note that serializing and deserializing an object can be an expensive operation. If you have to do this a lot in your code (inside loops), it can affect your performance.