Please advice how to convert a String
to JsonObject
using gson
library.
What I unsuccesfully do:
String stri
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
I do this, and it worked.
String emailData = {"to": "abc@abctest.com","subject":"User details","body": "The user has completed his training"
}
// Java model class
public class EmailData {
public String to;
public String subject;
public String body;
}
//Final Data
Gson gson = new Gson();
EmailData emaildata = gson.fromJson(emailData, EmailData.class);
Note that as of Gson 2.8.6, instance method JsonParser.parse
has been deprecated and replaced by static method JsonParser.parseString
:
JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
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();