【发布时间】:2020-10-23 15:01:44
【问题描述】:
当它们在服务器上可用时,我尝试构建一个应用程序来解析 android studio 中的一个或多个 json 数组。我的代码是:
`
private class DownloadImage extends AsyncTask<Void, Void, Bitmap> {
String name;
public DownloadImage(String name) {
this.name = name;
}
private void updateLabel() {
try {
HttpClient client = new DefaultHttpClient(getHttpRequestParams());
HttpGet getJson = new HttpGet(SERVER_ADRESS + "/objects.json");
HttpResponse jsonResponse = client.execute(getJson);
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
String label = jsonResult.objects.get(0).label;
TextView Result = (TextView) findViewById(R.id.textView);
Result.setText("Your instrument could be a " + label);}
} catch (Exception e) {
e.printStackTrace();
}
}
json文件为:
{"file": "image.jpg", "objects": [{"bbox": [257, 59, 544, 799], "label": "spanishguitar", "prob": 0.6061},]}
在这种情况下它有效!但有时 json 有两个“标签”数组,看起来像这样:
{"file": "image.jpg", "objects": [{"bbox": [257, 59, 544, 799], "label": "spanishguitar", "prob": 0.6061}, {"bbox": [247, 65, 546, 794], "label": "cavaquinho", "prob": 0.5541}]}
我的想法是像这样使用 if else:
if (200 == jsonResponse.getStatusLine().getStatusCode()) {
InputStream inputStream = jsonResponse.getEntity().getContent();
String json = IOUtils.toString(inputStream);
JsonResult jsonResult = new Gson().fromJson(json, JsonResult.class);
String label = jsonResult.objects.get(0).label;
String label2 = jsonResult.objects.get(1).label;
if (label2 != null){
TextView Result = (TextView) findViewById(R.id.textView);
Result.setText("Your instrument could be a " + label + " or a " + label2);
}
else {
TextView Result = (TextView) findViewById(R.id.textView);
Result.setText("Your instrument could be a " + label);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
当 label 和 label2 都在 json 文件中时,会打印输出(“您的乐器可能是西班牙吉他或 cavanquinho”)。是不是只有一个标签,没有输出。
你有什么想法吗?也许我完全错了?
【问题讨论】:
-
尝试打印完整的 json 响应以及
label和label2值到控制台或在调试模式下检查这些值。
标签: json android-studio gson