Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (2.6k points)

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?

1 Answer

0 votes
by (46k points)

Try JsonParser; for instance:

JsonParser parser = new JsonParser();

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

Related questions

0 votes
1 answer
asked Jul 29, 2019 in Java by Suresh (3.4k points)
0 votes
1 answer
0 votes
1 answer
0 votes
2 answers
+7 votes
2 answers

Browse Categories

...