【问题标题】:How to convert a String to JsonObject using gson library如何使用 gson 库将字符串转换为 JsonObject
【发布时间】:2011-07-04 22:44:22
【问题描述】:

请告知如何使用gson 库将String 转换为JsonObject

我没有成功的做法:

String string = "abcde";
Gson gson = new Gson();
JsonObject json = new JsonObject();
json = gson.toJson(string); // Can't convert String to JsonObject

【问题讨论】:

    标签: java json gson


    【解决方案1】:

    如果您想使用,可以将其转换为 JavaBean:

     Gson gson = new GsonBuilder().setPrettyPrinting().create();
     gson.fromJson(jsonString, JavaBean.class)
    

    要使用更灵活的 JsonObject,请使用以下内容:

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

    相当于如下:

    JsonElement jelem = gson.fromJson(json, JsonElement.class);
    JsonObject jobj = jelem.getAsJsonObject();
    

    【讨论】:

    • "Assert" 是额外的东西,它是为了测试目的。
    • jsonParser.parse(json).getAsJsonObject();
    • JsonObject jo = jsonParser.parse(json).getAsJsonObject();Assert.assertTrue(jo.get("Success").getAsBoolean());
    【解决方案2】:

    要以更简单的方式进行,请考虑以下内容:

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

    【讨论】:

      【解决方案3】:
      String string = "abcde"; // The String which Need To Be Converted
      JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);
      

      我这样做了,它奏效了。

      【讨论】:

        【解决方案4】:

        您不需要使用JsonObject。您应该使用 Gson 来转换 JSON 字符串和您自己的 Java 对象。

        Gson User Guide

        (序列化)

        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]
        

        (反序列化)

        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)
        

        【讨论】:

        • 但是我需要使用JsonObject。
        • 因为我的类的方法应该返回 JsonObject。
        • @Android:...为什么? JsonObject 是一个中间表示。在 99% 的用例中,您应该只关心将数据表示为 Java 对象或包含 JSON 的字符串。
        • 你没有回答这个问题 :) 当然有些情况下你确实需要将 String 转换为 JsonObject。
        • @MattBall 在 Ion http 库 (github.com/koush/ion) 中有一个函数可以将 http 请求的主体设置为 JsonObject。
        【解决方案5】:

        上面的答案似乎没有完全回答问题。

        我认为您正在寻找类似以下的内容:

        class TransactionResponse {
        
           String Success, Message;
           List<Response> Response;
        
        }
        
        TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);
        

        我的回答是这样的:

        {"Success":false,"Message":"Invalid access token.","Response":null}
        

        如您所见,变量名应与键值对中键的 Json 字符串表示形式相同。这会自动将您的 gson 字符串转换为 JsonObject。

        【讨论】:

        • 为什么在成员变量上使用大写?为什么使用默认访问修饰符?如果您想在响应中使用大写字母,请改用 @SerializedName("Success")
        【解决方案6】:
        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);
        

        【讨论】:

          【解决方案7】:
          Gson gson = new Gson();
          YourClass yourClassObject = new YourClass();
          String jsonString = gson.toJson(yourClassObject);
          

          【讨论】:

            【解决方案8】:
            JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");
            

            【讨论】:

              【解决方案9】:

              注意as of Gson 2.8.6,实例方法JsonParser.parse已被弃用并被静态方法JsonParser.parseString取代:

              JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();
              

              【讨论】:

                【解决方案10】:

                如果您只想将字符串转换为 json,请使用:

                使用 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 org.json.JSONException;
                import org.json.JSONObject;
                import org.json.JSONArray;
                

                现在将其转换为

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

                【讨论】:

                  猜你喜欢
                  • 2019-11-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2016-10-29
                  • 2015-09-16
                  • 2017-04-14
                  相关资源
                  最近更新 更多