-1

现在我正在做一个Android应用程序。现在我在json解析中遇到了一个问题。我的json页面结构是这样的。

[
{

"id":3,

"name":"dd"

},

{

"id":4,

"name":"ggg"

}

]

我尝试使用以下代码。

URL website = new URL("url");
InputStream in = website.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
JSONArray ary=new JSONArray(line);
}

但是我遇到了异常。因为所有数据都在不同的行中。如果它在同一行中 [{"id":3,"name":"dd"},{"id":4,"name":" ggg"}] 然后我可以轻松完成...但是他们在单独的行中提供所有数据..这就是问题..请帮助我的朋友

4

3 回答 3

2

Finaly I got..

    public void parseMovie(InputStream json) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(json));
        StringBuilder sb = new StringBuilder();
        String line = reader.readLine();
        while (line != null) {
            sb.append(line);
            line = reader.readLine();
        }
        reader.close();
        JSONArray jsonReply = new JSONArray(sb.toString()); 

        System.out.println("length is"+jsonReply.length());
        ArrayList<String> id=new ArrayList<String>();
        for (int i = 0; i < jsonReply.length(); i++) {
            JSONObject jsonMovie = jsonReply.getJSONObject(0); 


            id.add(jsonMovie.getString("id"));

        }


    }
于 2012-04-09T06:20:26.187 回答
0

尝试这个。

StringBuilder builder = new StringBuilder();
            HttpClient client = new DefaultHttpClient();

            HttpGet httpGet = new HttpGet("url");
            try {
                HttpResponse response = client.execute(httpGet);
                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();
                if (statusCode == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(content));
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                } else {
                    Log.v("in else", "Failed to download file");
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.v("Builder >>", builder.toString());
    String response=builder.toString();
于 2012-04-07T13:08:01.043 回答
0

首先获取整个数据,然后解析它:

StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
    sb.append(line);
}
JSONArray ary=new JSONArray(sb.toString());
于 2012-04-07T12:47:04.947 回答