Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson: Directly convert String to JsonObject (no POJO)

Tags:

java

json

gson

Can't seem to figure this out. I'm attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject. Is there a way to go directly from a String to JsonObject?

I've tried the following (Scala syntax):

val gson = (new GsonBuilder).create

val a: JsonObject = gson.toJsonTree("""{ "a": "A", "b": true }""").getAsJsonObject
val b: JsonObject = gson.fromJson("""{ "a": "A", "b": true }""", classOf[JsonObject])

but a fails, the JSON is escaped and parsed as a JsonString only, and b returns an empty JsonObject.

Any ideas?

like image 411
7zark7 Avatar asked Nov 05 '10 22:11

7zark7


4 Answers

use JsonParser; for example:

JsonObject o = JsonParser.parseString("{\"a\": \"A\"}").getAsJsonObject();
like image 55
Dallan Quass Avatar answered Oct 22 '22 22:10

Dallan Quass


Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();
like image 44
maverick Avatar answered Oct 22 '22 20:10

maverick


String jsonStr = "{\"a\": \"A\"}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
like image 30
Purushotham Avatar answered Oct 22 '22 22:10

Purushotham


The simplest way is to use the JsonPrimitive class, which derives from JsonElement, as shown below:

JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();
like image 41
Jozef Benikovský Avatar answered Oct 22 '22 22:10

Jozef Benikovský