【问题标题】:Missing keys in JSON format缺少 JSON 格式的键
【发布时间】:2015-09-08 07:47:23
【问题描述】:

我正在尝试在 Android 中解析动态的 JSON 字符串。这是一个非常简单的 JSON 结构。类似于以下内容:

  {
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
}    

但有时我没有得到一些钥匙。例如,键“b”可能会丢失。然后我的代码生成一个 JSONParser 异常。并且无法解析进一步的 JSON 字符串。

那么有什么方法可以忽略丢失的键吗?我尝试了optString();,但这仅适用于字符串情况,那么 JSONObject 和 JSONArray 呢? optJSONArray()optJSONObject() 不起作用。

有什么想法或解决方案吗?

【问题讨论】:

  • “optJSONArray() 和 optJSONObject() 不起作用” - 究竟是什么不起作用?请更具体。
  • 如果我尝试从缺少的键中获取相应 JSONObject 和 JSONParser 的值,则 getJSONArray("key") 和 getJSONObject("key") 返回异常。我使用了 optJSONArray("key") 和 optJSONObject("key") 但问题仍然存在

标签: android json exception


【解决方案1】:

我认为最简单的方法是使用 GSON!

您只需创建一个普通的旧 Java 对象 (POJO) 来表示您想要的数据,然后让 GSON 完成剩下的工作。如果 json 字符串中不存在该值,它将被设置为该类型的“默认值”(通常为 null,但对于整数为 0,对于布尔值等为 false...)

要包含在您的 Android Studio 项目中:

compile 'com.google.code.gson:gson:2.2.4'

还可以查看this page,特别注意“对象示例”标题,了解如何使用 GSON。

【讨论】:

    【解决方案2】:

    您可以使用 belo 找到动态密钥

        String jsonString = "{ \"a\": 1, \"b\": 2, \"c\": 3, \"d\": 4, \"e\": 5 }";
    
    
    
    try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject issueObj = new JSONObject(jsonString);
            Iterator iterator = issueObj.keys();
            while(iterator.hasNext()){
                String key = (String)iterator.next();
    
                Integer value = (Integer) issueObj.get(key);
                Log.d(TAG,"value: "+value);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    

    或者您可以使用 GSON。

    【讨论】:

      【解决方案3】:

      您可以尝试使用 GSON 将该 JSONObject 转换为 Map,如下所示:

              String json1 = "{\n" +
                      "    \"a\": 1,\n" +
                      "    \"b\": 2,\n" +
                      "    \"c\": 3,\n" +
                      "    \"d\": 4,\n" +
                      "    \"e\": 5\n" +
                      "}";
              Gson gson1 = new Gson();
              Type type1 = new TypeToken<Map<String, Integer>>(){}.getType();
              Map<String, Integer> myMap1 = gson1.fromJson(json1, type1);
      

      在您的 build.gradle 文件中:

      compile 'com.google.code.gson:gson:2.3.1'
      

      【讨论】:

        猜你喜欢
        • 2014-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-21
        • 2013-06-15
        • 2014-01-04
        • 1970-01-01
        相关资源
        最近更新 更多