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
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.
String myJSONString = "{'test': '100.00'}"; JsonObject jobj = new Gson(). fromJson(myJSONString, JsonObject. class); String result = jobj. get("test").
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.
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();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With