331

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?

Vadzim
  • 24,954
  • 11
  • 143
  • 151
7zark7
  • 10,015
  • 5
  • 39
  • 54
  • 2
    Beware of gson validation pitfalls: https://stackoverflow.com/questions/43233898/how-to-check-if-json-is-valid-in-java-using-gson/47890960#47890960 – Vadzim Dec 19 '17 at 16:20

10 Answers10

559

use JsonParser; for example:

JsonObject o = JsonParser.parseString("{\"a\": \"A\"}").getAsJsonObject();
khateeb
  • 5,265
  • 15
  • 58
  • 114
Dallan Quass
  • 5,921
  • 1
  • 17
  • 8
  • 18
    ugh should have a static 1 liner convenience method – Blundell Dec 06 '13 at 12:36
  • no static example, but plenty of one liner examples below – Yaniv May 04 '14 at 11:10
  • 44
    the cast to JsonObject is unnecessary, better use `new JsonParser().parse(..).getAsJsonObject();` – Chriss Jul 18 '14 at 11:46
  • I think [...].getAsJsonObject() is the right implementation. Casting seems like an overkill to me and not too clean. – FeleMed Oct 23 '14 at 18:30
  • Note that it can throw 3 exceptions per the [docs](http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/JsonParser.html#parse(com.google.gson.stream.JsonReader)) – Kevin Meredith Dec 05 '14 at 22:12
  • 1
    I guess JsonParser is an abstract class – Jatin Sehgal Mar 30 '15 at 11:08
  • 1
    @KevinMeredith you link is broken ,use [this](https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonParser.html#parse-java.lang.String-) please – Ninja Feb 07 '17 at 06:54
  • Dallan Quass - I have a class with many static methods which can make different api calls. Should I have one instance of JsonParser for the class or should I create one in each static method ? – MasterJoe May 17 '19 at 18:01
  • @MasterJoe2 I'm hoping others will answer your question, or maybe you want to post it as a new question? I haven't been around java for awhile. – Dallan Quass May 23 '19 at 02:34
  • 15
    Note that this method is now deprecated. Use `JsonParser.parseString(str).getAsJsonObject()`. – Michael Röhrig Nov 29 '19 at 13:45
  • In my case, i needed it as string, so i used this: `String data = new Gson().toJson(JsonParser.parseString("{type: someValue}"));` – Neoraptor Mar 18 '20 at 04:27
  • This seems like it could be a performance hit if you have to parse the string when you already have knowledge that it's a `JsonPrimitve`. But I don't see another way. – Sridhar Sarnobat Aug 25 '22 at 00:26
149

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

JsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();
Ram Ghadiyaram
  • 28,239
  • 13
  • 95
  • 121
maverick
  • 2,902
  • 2
  • 19
  • 15
  • 2
    For some reason it wraps with `members` parent key. Here is a sample { "members" : { "key1" : "13756963814f2c594822982c0307fb81", "key2" : true, "key3" : 123456789 } } – Hossain Khan Nov 15 '13 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 '15 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();` – Jimmy Garpehäll Dec 06 '19 at 09:26
62
String jsonStr = "{\"a\": \"A\"}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();
Purushotham
  • 3,770
  • 29
  • 41
  • can you validate my answer with GSON way for convert List data to jsonobject by gson http://stackoverflow.com/questions/18442452/create-an-array-of-json-objects/18443395#18443395 – LOG_TAG Aug 26 '13 at 11:59
  • 3
    I have validated your answer. – Purushotham Feb 07 '14 at 05:47
  • @knoxxs, You mean `JsonObject` class definition? It comes from Google's Gson library. You can refer the documentation [here](http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html). – Purushotham Apr 09 '15 at 10:31
  • 1
    This gives me an error complaining about JsonElement not having a no-arg constructor. – clapas May 28 '15 at 14:19
42

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();
Jozef Benikovský
  • 1,121
  • 10
  • 9
11

Just encountered the same problem. You can write a trivial custom deserializer for the JsonElement class:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

GsonBuilder gson_builder = new GsonBuilder();
gson_builder.registerTypeAdapter(
        JsonElement.class,
        new JsonDeserializer<JsonElement>() {
            @Override
            public JsonElement deserialize(JsonElement arg0,
                    Type arg1,
                    JsonDeserializationContext arg2)
                    throws JsonParseException {

                return arg0;
            }
        } );
String str = "{ \"a\": \"A\", \"b\": true }";
Gson gson = gson_builder.create();
JsonElement element = gson.fromJson(str, JsonElement.class);
JsonObject object = element.getAsJsonObject();
dikkini
  • 1,184
  • 1
  • 23
  • 52
Dan Menes
  • 6,667
  • 1
  • 33
  • 35
7

The JsonParser constructor has been deprecated. Use the static method instead:

JsonObject asJsonObject = JsonParser.parseString(someString).getAsJsonObject();
Stephen Paul
  • 37,253
  • 15
  • 92
  • 74
4

I believe this is a more easy approach:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically.

2

Came across a scenario with remote sorting of data store in EXTJS 4.X where the string is sent to the server as a JSON array (of only 1 object).
Similar approach to what is presented previously for a simple string, just need conversion to JsonArray first prior to JsonObject.

String from client: [{"property":"COLUMN_NAME","direction":"ASC"}]

String jsonIn = "[{\"property\":\"COLUMN_NAME\",\"direction\":\"ASC\"}]";
JsonArray o = (JsonArray)new JsonParser().parse(jsonIn);

String sortColumn = o.get(0).getAsJsonObject().get("property").getAsString());
String sortDirection = o.get(0).getAsJsonObject().get("direction").getAsString());
c2willi
  • 106
  • 3
1
//import com.google.gson.JsonObject;  
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");
Maddy
  • 316
  • 1
  • 6
  • 14
1

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();
Hossein Kurd
  • 3,184
  • 3
  • 41
  • 71