Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I have a org.json.JSONObject object.

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

Thanks

like image 896
special0ne Avatar asked Aug 06 '15 22:08

special0ne


People also ask

What is the difference between JSONObject and JSONObject?

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.

How do I change the value of a JSONObject?

JSONObject js = new JSONObject(); js. put("name", "rai"); js. remove("name"); js. put("name", "abc");

Can we convert JSONObject to string?

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.

What does GSON from JSON do?

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.


1 Answers

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.

like image 170
Scott Schechter Avatar answered Oct 21 '22 19:10

Scott Schechter