从json获取数据

时间:2013-09-16 13:34:06

标签: android json web-services

我第一次这样做需要帮助。我有一个json文件 https://api.github.com/gists/public 我想在用户标签下获取其数据“login”和“id”。请帮助。

查看示例我尝试从以下代码中获取数据并将内容放入日志中,但日志内容和URL中的内容是不同的。

try {
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI("https://api.github.com/gists/public"));
            HttpResponse response = client.execute(request);
            InputStream ips = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
                    "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while (true) {
                s = buf.readLine();
                if (s == null || s.length() == 0)
                    break;
                sb.append(s);
                JSONArray ja = new JSONArray(s);

                for (int i = 0; i < ja.length(); i++) {
                    JSONObject jo = (JSONObject) ja.get(i);
                    //items.add(jo.getString("text"));
                    Log.v("json", "json object : " + jo.getString("user"));
                }
                Log.v("json", "json file : " + sb);
            }
            buf.close();
            ips.close();

        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // any cleanup code...
        }

1 个答案:

答案 0 :(得分:0)

实际上"user"JSONObject,所以首先你必须得到JSONObject,然后在其中获取String。在for循环中执行此操作。

JSONObject obj = jo.getJSONObject("user");
String login = obj.getString("login");
String id = obj.getString("id");