I am writing a java code in which i need to convert a JSONObject to JsonElement.Is there any way using which i can convert a JSONObject (org.json) to JsonElement(com.google.gson)?
GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.
String myJSONString = "{'test': '100.00'}"; JsonObject jobj = new Gson(). fromJson(myJSONString, JsonObject. class); String result = jobj. get("test").
A class representing an element of Json. It could either be a JsonObject , a JsonArray , a JsonPrimitive or a JsonNull .
1 Answer 1. 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());
A class representing an element of Json. It could either be a JsonObject, a JsonArray, a JsonPrimitive or a JsonNull. convenience method to get this element as a JsonObject. If the element is of some other type, a Ille convenience method to get this element as a JsonArray. If the element is of some other type, a Illeg
convenience method to get this element as a JsonArray. If the element is of some other type, a IllegalStateException will result. Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonArray () first. get this element as a JsonArray.
Hence it is best to use this method after ensuring that this element is of the desired type by calling isJsonPrimitive () first. get this element as a JsonPrimitive. java.lang.IllegalStateException - if the element is of another type. convenience method to get this element as a JsonNull.
One way that always works is to serialize the object to JSON and then parse it again:
JSONObject myData = ...
Gson gson = new Gson();
JsonElement element = gson.fromJson(myData.toString(), JsonElement.class);
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