java - 错误: unreported exception JSONException in Android

标签 java android json retrofit

所以基本上我所做的是在我的类 FlagReportStamped 中创建了一个 map ,并通过 map.keyset 通过键迭代它,现在我有了这种类型错误

error: unreported exception JSONException; must be caught or declared to be thrown

任何人都可以帮助我重构我的代码,我只是这里的初学者。

Activity 类别:

      //flagreport
      final Call<FlagReportStamped> callFlagReport = jsonAPI.getReportID();
      callFlagReport.enqueue(new Callback<FlagReportStamped>() {
          @Override
          public void onResponse(Call<FlagReportStamped> call, Response<FlagReportStamped> response) {

              if (!response.isSuccessful()) {
                  Log.e("mainAction", "Code: " + response.code());
                  return;
              }


              JSONObject jObject = new JSONObject(response.body().getFlagReport().getMap());
              Iterator<?> keys = jObject.keys();

              while( keys.hasNext() ){
                  String key = (String)keys.next();
                  boolean value = jObject.getBoolean(key); // I get an error here
                  SpannableString ss = new SpannableString(key);//text to change color
                  ss.setSpan(new ForegroundColorSpan(value ? Color.BLUE: Color.RED), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                  flagName.append(ss);
              }

          }

          @Override
          public void onFailure(Call<FlagReportStamped> call, Throwable t) {
              call.cancel();
          }
      });
  }

基本上,我在这里想做的是仅显示 json 中的对象名称,而不是显示它们的值/状态,我也仅将其迭代到它们的对象名称并更改其颜色取决于他们的值(value)观/状态。

最佳答案

以下行出现问题,因为您的响应字符串可能不是 json 对象格式。这就是为什么你被迫抛出 json 异常

JSONObject jObject = new JSONObject(response.body().getFlagReport().getMap());

所以用 try block 覆盖你的解析 fragment

try{
       JSONObject jObject = new JSONObject(response.body().getFlagReport().getMap());
            Iterator<?> keys = jObject.keys();
        while( keys.hasNext() ){
            String key = (String)keys.next();
            boolean value = jObject.getBoolean(key); // I get an error here
            SpannableString ss = new SpannableString(key);//text to change color
            ss.setSpan(new ForegroundColorSpan(value ? Color.BLUE: Color.RED), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            flagName.append(ss);
        }
    }catch(JSONException e){
       e.printStacktrace();
    }

关于java - 错误: unreported exception JSONException in Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59280227/

相关文章:

android - 许多 AsyncTask 生成时出现 AsyncTask 性能问题。

android - 为什么游标永远不会为空?

javascript - 检索 POST JSON 响应

c# - 如何修复 json 到 c# 类的转换?

android - Flutter - 为 API 实现 JSON getter

Java:打印文件不起作用

java - Wicket ListView 不刷新

java - 确保标题在 JOptionPane 上完全可见

java - 使用 Apache Tomcat 将上传的静态文件存储在何处

android - EditText 的 TextWatcher 验证器