Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject (org.json) to JsonElement(com.google.gson)

Tags:

java

json

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)?

like image 751
AS-Sher Avatar asked Nov 17 '16 12:11

AS-Sher


People also ask

What is difference between JSON and GSON?

GSON can use the Object definition to directly create an object of the desired type. While JSONObject needs to be parsed manually.

How do you read a GSON value?

String myJSONString = "{'test': '100.00'}"; JsonObject jobj = new Gson(). fromJson(myJSONString, JsonObject. class); String result = jobj. get("test").

What is Jsonelement in Java?

A class representing an element of Json. It could either be a JsonObject , a JsonArray , a JsonPrimitive or a JsonNull .

How to convert JSON object to JSON object?

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());

How to get the element of a JSON object?

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

How to get this element as a jsonarray in Java?

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.

When to use isjsonprimitive() method in Java?

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.


1 Answers

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);
like image 54
fafl Avatar answered Sep 28 '22 07:09

fafl