How to convert a String to JsonObject using gson library

后端 未结 9 1177
既然无缘
既然无缘 2020-11-30 23:45

Please advice how to convert a String to JsonObject using gson library.

What I unsuccesfully do:

String stri         


        
相关标签:
9条回答
  • 2020-12-01 00:17
    JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
    
    0 讨论(0)
  • 2020-12-01 00:20
    String string = "abcde"; // The String which Need To Be Converted
    JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
    

    I do this, and it worked.

    0 讨论(0)
  • 2020-12-01 00:20
    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);
    
    0 讨论(0)
  • 2020-12-01 00:20

    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();
    
    0 讨论(0)
  • 2020-12-01 00:22
    Gson gson = new Gson();
    YourClass yourClassObject = new YourClass();
    String jsonString = gson.toJson(yourClassObject);
    
    0 讨论(0)
  • 2020-12-01 00:25

    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();
    
    0 讨论(0)
提交回复
热议问题