336

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

10 Answers 10

565

use JsonParser; for example:

JsonObject o = JsonParser.parseString("{\"a\": \"A\"}").getAsJsonObject(); 
Sign up to request clarification or add additional context in comments.

12 Comments

ugh should have a static 1 liner convenience method
the cast to JsonObject is unnecessary, better use new JsonParser().parse(..).getAsJsonObject();
I guess JsonParser is an abstract class
@KevinMeredith you link is broken ,use this please
Note that this method is now deprecated. Use JsonParser.parseString(str).getAsJsonObject().
|
151

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

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

3 Comments

For some reason it wraps with members parent key. Here is a sample { "members" : { "key1" : "13756963814f2c594822982c0307fb81", "key2" : true, "key3" : 123456789 } }
Use the latest gson library, like 2.2.4. The version like 2.2.2 adds members tag for some reason.
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();
62
String jsonStr = "{\"a\": \"A\"}"; Gson gson = new Gson(); JsonElement element = gson.fromJson (jsonStr, JsonElement.class); JsonObject jsonObj = element.getAsJsonObject(); 

4 Comments

can you validate my answer with GSON way for convert List data to jsonobject by gson stackoverflow.com/questions/18442452/…
I have validated your answer.
@knoxxs, You mean JsonObject class definition? It comes from Google's Gson library. You can refer the documentation here.
This gives me an error complaining about JsonElement not having a no-arg constructor.
43

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(); 

1 Comment

This is the simplest answer and helped me out. Thanks!
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(); 

Comments

8

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

JsonObject asJsonObject = JsonParser.parseString(someString).getAsJsonObject(); 

Comments

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.

Comments

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()); 

Comments

1
//import com.google.gson.JsonObject; JsonObject complaint = new JsonObject(); complaint.addProperty("key", "value"); 

2 Comments

Above is the easiest way to convert your key-value data to gson object.
Thanks, in my case I had an unparsed JSON string which I needed to start from.
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(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.