[java] How to convert a String to JsonObject using gson library

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

This question is related to java json gson

The answer is


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)

String emailData = {"to": "[email protected]","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);

String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.


JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");

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.


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

To do it in a simpler way, consider below:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();

Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to gson

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $ Gson library in Android Studio how to parse JSON file with GSON Convert Map to JSON using Jackson "Expected BEGIN_OBJECT but was STRING at line 1 column 1" Representing null in JSON Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 How to parse JSON Array (Not Json Object) in Android Parsing JSON array into java.util.List with Gson Using GSON to parse a JSON array