Gson: Directly convert String to JsonObject (no POJO)

7zark7 picture 7zark7 · Nov 5, 2010 · Viewed 324.7k times · Source

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?

Answer

Dallan Quass picture Dallan Quass · Dec 24, 2010

use JsonParser; for example:

JsonParser parser = new JsonParser();
JsonObject o = parser.parse("{\"a\": \"A\"}").getAsJsonObject();