【问题标题】:How to use Gson to parse dynamic object into JSONObject如何使用 Gson 将动态对象解析为 JSONObject
【发布时间】:2016-07-18 06:23:54
【问题描述】:

有没有办法使用 Gson 将这样的 JSON 响应解析到下面的模型类中?

{
    "id": 123,
    "phone": "123456789",
    "config": {
        "dynamicKey1": "true",
        "dynamicKey2": "123"
    }
}

模型类:

public class User {
    int id;
    String phone;
    JSONObject config;
}

config 对象中的键可能存在也可能不存在。 反序列化后,我希望能够使用 user.getConfig().optBoolean("dynamicKey1") 之类的东西动态查询配置键

【问题讨论】:

    标签: json parsing gson jsonobject


    【解决方案1】:

    我最终做的是使用com.google.gson.JsonObject 而不是org.json.JSONObject。使用来自 Gson 的JsonObject,反序列化工作完美,访问动态键看起来像这样:

    user.getConfig().getAsJsonPrimitive("dynamicKey1").getAsBoolean()
    

    【讨论】:

      【解决方案2】:

      用户配置:

      public class User {
      
      int id;
      String phone;
      Map<String, String> config;
      public int getId() {
          return id;
      }
      public void setId(int id) {
          this.id = id;
      }
      public String getPhone() {
          return phone;
      }
      public void setPhone(String phone) {
          this.phone = phone;
      }
      public Map<String, String> getConfig() {
          return config;
      }
      public void setConfig(Map<String, String> config) {
          this.config = config;
      }
      
      }
      

      主类:

          public static void main(String[] args) {
          // TODO Auto-generated method stub
          String input = "{\"id\": 123,\"phone\": \"123456789\",\"config\": {\"dynamicKey1\": \"true\",\"dynamicKey2\": \"123\"}}";
      
          Gson gsonInstance = null;
      
          gsonInstance = new GsonBuilder().create();
      
          User user = gsonInstance.fromJson(input, User.class);
      
          boolean value = Boolean.parseBoolean(user.getConfig().get("dynamicKey1"));
          System.out.println(value);
      }
      

      您可以通过这种方式在 Config 部分创建 DynamicKeys 的映射,然后在需要时转换为相应的原始类型。

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多