Categories
gson java json

Gson: Directly convert String to JsonObject (no POJO)

326

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

554

use JsonParser; for example:

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

12

  • 18

    ugh should have a static 1 liner convenience method

    – Blundell

    Dec 6, 2013 at 12:36

  • 44

    the cast to JsonObject is unnecessary, better use new JsonParser().parse(..).getAsJsonObject();

    – Chriss

    Jul 18, 2014 at 11:46


  • 1

    I guess JsonParser is an abstract class

    Mar 30, 2015 at 11:08

  • 1

    @KevinMeredith you link is broken ,use this please

    – Ninja

    Feb 7, 2017 at 6:54

  • 14

    Note that this method is now deprecated. Use JsonParser.parseString(str).getAsJsonObject().

    Nov 29, 2019 at 13:45

149

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

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

3

  • 2

    For some reason it wraps with members parent key. Here is a sample { “members” : { “key1” : “13756963814f2c594822982c0307fb81”, “key2” : true, “key3” : 123456789 } }

    Nov 15, 2013 at 20:01


  • 1

    Use the latest gson library, like 2.2.4. The version like 2.2.2 adds members tag for some reason.

    – Rubin Yoo

    Feb 13, 2015 at 23:12

  • 5

    JsonParser().parse() is deprecated in newer versions of Gson. Use JsonObject jsonObj = JsonParser.parseString(str).getAsJsonObject()or Gson gson = new Gson(); JsonElement element = gson.fromJson (jsonStr, JsonElement.class); JsonObject jsonObj = element.getAsJsonObject();

    Dec 6, 2019 at 9:26

61

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

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();

4

  • can you validate my answer with GSON way for convert List data to jsonobject by gson stackoverflow.com/questions/18442452/…

    – LOG_TAG

    Aug 26, 2013 at 11:59


  • 3

    I have validated your answer.

    Feb 7, 2014 at 5:47

  • @knoxxs, You mean JsonObject class definition? It comes from Google’s Gson library. You can refer the documentation here.

    Apr 9, 2015 at 10:31

  • 1

    This gives me an error complaining about JsonElement not having a no-arg constructor.

    – clapas

    May 28, 2015 at 14:19