Please advice how to convert a String
to JsonObject
using gson
library.
What I unsuccesfully do:
String stri
You don't need to use JsonObject
. You should be using Gson to convert to/from JSON strings and your own Java objects.
See the Gson User Guide:
(Serialization)
Gson gson = new Gson(); gson.toJson(1); // prints 1 gson.toJson("abcd"); // prints "abcd" gson.toJson(new Long(10)); // prints 10 int[] values = { 1 }; gson.toJson(values); // prints [1]
(Deserialization)
int one = gson.fromJson("1", int.class); Integer one = gson.fromJson("1", Integer.class); Long one = gson.fromJson("1", Long.class); Boolean false = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String anotherStr = gson.fromJson("[\"abc\"]", String.class)
Looks like the above answer did not answer the question completely.
I think you are looking for something like below:
class TransactionResponse {
String Success, Message;
List<Response> Response;
}
TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
where my response is something like this:
{"Success":false,"Message":"Invalid access token.","Response":null}
As you can see, the variable name should be same as the Json string representation of the key in the key value pair. This will automatically convert your gson string to JsonObject.
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();