I have a org.json.JSONObject
object.
What's the easiest way to create a gson.JsonObject
object from it?
Thanks
JSONObject is "native" to Android SDK, JsonObject is probably the one from Gson library, the one that I use. Two different package, don't work with both ;) choose one. I had some issue with the date formatting in JSONObject.
JSONObject js = new JSONObject(); js. put("name", "rai"); js. remove("name"); js. put("name", "abc");
Stringify a JavaScript Objectstringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.
Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then, toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With