How to convert a String to JsonObject using gson library

后端 未结 9 1313
既然无缘
既然无缘 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: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();
    

提交回复
热议问题