107

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
Jonik
  • 80,077
  • 70
  • 264
  • 372
Eugene
  • 59,186
  • 91
  • 226
  • 333

11 Answers11

190

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();
eadjei
  • 2,066
  • 2
  • 14
  • 7
49

To do it in a simpler way, consider below:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
user2285078
  • 501
  • 5
  • 6
35
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.

CalvinChe
  • 975
  • 8
  • 8
29

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)
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
9
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);
Draken
  • 3,134
  • 13
  • 34
  • 54
BAIJU SHARMA
  • 276
  • 4
  • 9
8

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.

animuson
  • 53,861
  • 28
  • 137
  • 147
Triguna
  • 107
  • 1
  • 1
  • 1
    Why do you use uppercase on member variables? Why do you use default access modifier? If you want uppercase in the response then use `@SerializedName("Success")` for instance instead. – Simon Zettervall Oct 30 '13 at 09:41
4
Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
Trinadh Koya
  • 1,089
  • 15
  • 19
4

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();
Christian S.
  • 877
  • 2
  • 9
  • 20
3
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
s.alem
  • 12,579
  • 9
  • 44
  • 72
Nadhas
  • 5,421
  • 2
  • 28
  • 42
0

if you just want to convert string to json then use:

use org.json: https://mvnrepository.com/artifact/org.json/json/20210307

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

import these

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

Now convert it as

//now you can convert string to array and object without having complicated maps and objects
 
try {
 JSONArray jsonArray = new JSONArray("[1,2,3,4,5]");
 //you can give entire jsonObject here 
 JSONObject jsonObject= new JSONObject("{\"name\":\"test\"}") ;
             System.out.println("outputarray: "+ jsonArray.toString(2));
             System.out.println("outputObject: "+ jsonObject.toString(2));
        }catch (JSONException err){
            System.out.println("Error: "+ err.toString());
        }
PDHide
  • 18,113
  • 2
  • 31
  • 46
0

You can use the already Gson existing method :

inline fun <I, reified O> I.convert():O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 11 '22 at 03:30