Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a String to JsonObject using gson library

Tags:

java

json

gson

Please advice how to convert a String to JsonObject using gson library.

What I unsuccesfully do:

String string = "abcde"; Gson gson = new Gson(); JsonObject json = new JsonObject(); json = gson.toJson(string); // Can't convert String to JsonObject 
like image 587
Eugene Avatar asked Feb 26 '11 17:02

Eugene


People also ask

How do you convert a string to a JSON object in Python?

Use the json. you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

How do you get string from GSON?

String myJSONString = "{'test': '100.00'}"; JsonObject jobj = new Gson(). fromJson(myJSONString, JsonObject. class); String result = jobj. get("test").

Is GSON a string?

Overview. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at http://code.google.com/p/google-gson.


2 Answers

You can convert it to a JavaBean if you want using:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();  gson.fromJson(jsonString, JavaBean.class) 

To use JsonObject, which is more flexible, use the following:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}"; JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject)jsonParser.parse(json); Assert.assertNotNull(jo); Assert.assertTrue(jo.get("Success").getAsString()); 

Which is equivalent to the following:

JsonElement jelem = gson.fromJson(json, JsonElement.class); JsonObject jobj = jelem.getAsJsonObject(); 
like image 190
eadjei Avatar answered Sep 26 '22 17:09

eadjei


To do it in a simpler way, consider below:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject(); 
like image 37
user2285078 Avatar answered Sep 24 '22 17:09

user2285078