2013-09-16 67 views
0

第一次我這樣做,所以需要幫助。我有一個json文件 https://api.github.com/gists/public 我想在其用戶標籤下取得它的數據只有「login」和「id」。請幫助。json的數據提取

看看這些例子,我嘗試從下面的代碼中獲取數據並將內容放入日誌中,但日誌內容和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... 
     } 
+0

也放置您的JSON ARRAY在這裏,將更清楚如何解決它 –

回答

0

其實"user"JSONObject,所以,首先你必須拿到JSONObject,然後在其中獲取String秒。在for循環中執行此操作。

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

謝謝你,我節省了時間:) – jad