我做了一个 http 客户端,并且收到了响应。我正在使用 JSONObject 来解析数据,当我执行下面的代码时,它会很好地打印出所有 JSON
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if(entity!=null){
try(InputStream instream = entity.getContent()) {
String responseString = readInputStream(instream);
JSONObject job = new JSONObject(responseString);
statusLabel.setText("Command Result: " + job.toString());
这是 readInputSream 函数:
static private String readInputStream(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream, "UTF-8"));
String tmp;
StringBuilder sb = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
sb.append(tmp).append("\n");
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '\n') {
sb.setLength(sb.length() - 1);
}
reader.close();
return sb.toString();
}
如果我将其从 job.toString() 更改为:
statusLabel.setText("Command Result: " + job.get("result"));
它打印出正确的 1,它一直工作到 my_list。我不确定如何解析该列表。我在下面放了一个回复的片段。我尝试过“my_list”、“my_list[]”、my_list[0]”,但没有任何效果。我得到 JSONObject“blank” not find
{"result":1, "ver":1,"total":2,"catch":true,"my_list":[{"id":3,"mid":0,"format":3,"user":4,"property":1,"type":0,"title":"hello","start":146,"end":1464,"hid":3,"bid":1,"reason":1,"time":0,"creator":"1","hello":0,"my":0,"year":"0","ggg":614,"name":"","ch":"0","attr":0,"type":1,"vtype":1,"tm_log": {"fr":4,"action":0,"vr":"82","started":1,"av_ended":2,"tr":1}}
最佳答案
您尝试检索的元素被解析为 JSONArray,而不是 JSONObject。尝试:
JSONArray my_list = job.getJSONArray("my_list");
关于java - 在java中解析JSON响应(包括列表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37596793/