所以基本上我所做的是在我的类 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/