从响应字符串中提取数组

时间:2013-08-13 13:18:50

标签: java arrays json string type-conversion

我在节点中有如下的响应,如何将其解压缩为java中的数组

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

注意:最后那些人,抱歉浪费你们的时间,看到我的最后评论:)

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

我正在获取上面指定的字符串,我想要的是如何将字符串转换为数组,以便我可以循环访问数组中的对象

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."
   }
]

现在我怎么能循环呢

1 个答案:

答案 0 :(得分: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"));
}