0

我有一个来自节点的如下响应我如何将它提取为java中的数组

[
   {
      "userName":"Steve",
      "date":"Tue Aug 13 18:44:23 GMT+05:30 2013",
      "message":"Good morning sir."
   }
]

注意:终于做到了,对不起,浪费了你们时间,请参阅我的最后评论:)

我正在向服务器写入节点发出 http 请求,并且在服务器中我将对象数组 [{}, {}, ...] 发送回 java,现在来到 java,我将使用读取响应InputStream 并构造结果字符串。

我得到了上面指定的字符串,我想要的是如何将字符串转换为数组,以便我可以循环并访问数组中的对象

HttpGet httpget = new HttpGet('some uri');
HttpEntity httpentity = httpclient.execute(httpget).getEntity();

private void renderResponseAndQueueResults(HttpEntity httpentity) {
                try {
                    InputStream is = httpentity.getContent();
                    String result = convertStreamToString(is);
                    is.close();
                    appendResultToMap(result);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            private String convertStreamToString(InputStream is) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;

                try {
                    while( (line = reader.readLine()) != null){
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally{
                    try{
                        is.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
                return sb.toString();
            }

convertStreamToString 的返回是一个类似的字符串

[
   {
      "userName":"Steve",
      "date":"Tue Aug 13 18:44:23 GMT+05:30 2013",
      "message":"Good morning sir."
   }
]

现在我怎么能循环通过它

4

1 回答 1

0

您需要参考 JSON 库 API: http: //www.json.org/javadoc/org/json/JSONArray.html

这可能是您想要的:

//process the JSON array parsed out from the source string
for (int i = 0; i < arr .length(); i++) 
{
    //get each JSON object of the array
    JSONObject iObj = arr.getJSONObject(i);

    //access the content of the JSON object, like print it
    System.out.println(iObj.getString("userName"));
}
于 2013-08-13T13:52:52.240 回答