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

21,903

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.

Share:
21,903
special0ne
Author by

special0ne

Updated on July 19, 2022

Comments

  • special0ne
    special0ne almost 2 years

    I have a org.json.JSONObject object.

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

    Thanks