2014-12-26 68 views
0

嘿傢伙我需要幫助提取JSON值。我試着解析,但結果不出來。JSON幫助HTTPGET返回

繼承人我java代碼:

public class MyAct extends Activity { 

    EditText etResponse; 
    TextView tvIsConnected; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.result); 
     String s = getIntent().getStringExtra("username"); 

     // get reference to the views 
     etResponse = (EditText) findViewById(R.id.etResponse); 
     tvIsConnected = (TextView) findViewById(R.id.tvIsConnected); 

     // check if you are connected or not 
     if(isConnected()){ 
      tvIsConnected.setBackgroundColor(0xFF00CC00); 
      tvIsConnected.setText("You are connected"); 
     } 
     else{ 
      tvIsConnected.setText("You are NOT conncted"); 
     } 

     // show response on the EditText etResponse 
     //etResponse.setText(GET("http://hmkcode.com/examples/index.php")); 

     // call AsynTask to perform network operation on separate thread 

     new HttpAsyncTask().execute("https://api.github.com/users/" + s + "/repos"); 
    } 

    public static String GET(String url){ 
     InputStream inputStream = null; 
     String result = ""; 
     String dat = ""; 

     try { 

      // create HttpClient 
      HttpClient httpclient = new DefaultHttpClient(); 

      // make GET request to the given URL 
      HttpResponse httpResponse = httpclient.execute(new HttpGet(url)); 

      // receive response as inputStream 
      inputStream = httpResponse.getEntity().getContent(); 

      // convert inputstream to string 
      if(inputStream != null) { 
       result = convertInputStreamToString(inputStream); 
       dat = result; 
      } 
      else 
       result = "Did not work!"; 

     } catch (Exception e) { 
      Log.d("InputStream", e.getLocalizedMessage()); 
     } 

     return result; 
    } 

    private static String convertInputStreamToString(InputStream inputStream) throws IOException{ 
     BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
     String line = ""; 
     String result = ""; 
     while((line = bufferedReader.readLine()) != null) 
      result += line; 

     inputStream.close(); 
     return result; 

    } 

    public boolean isConnected(){ 
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE); 
     NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); 
     if (networkInfo != null && networkInfo.isConnected()) 
      return true; 
     else 
      return false; 
    } 

    private class HttpAsyncTask extends AsyncTask<String, Void, String> { 
     @Override 
     protected String doInBackground(String... urls) { 

      return GET(urls[0]); 
     } 
     // onPostExecute displays the results of the AsyncTask. 
     @Override 
     protected void onPostExecute(String result) { 
      Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show(); 
      etResponse.setText(result); 
     } 
    } 

} 

輸出我收到這個樣子的:

[ 
    { 
    "id": 8432681, 
    "name": "dispersy", 
    "full_name": "Tribler/dispersy", 
    "owner": { 
     "login": "Tribler", 
     "id": 2913489, 
     "avatar_url": "", 
     "gravatar_id": "", 
     "url": "", 
      "type": "Organization", 
     "site_admin": false 
    }, 
    "private": false, 
     "size": 8960, 
    "stargazers_count": 28, 
    "watchers_count": 28, 
    "language": "Python", 
    "has_issues": true, 
    "has_downloads": true, 
    "has_wiki": true, 
    "has_pages": false, 
    "forks_count": 19, 
    "mirror_url": null, 
    "open_issues_count": 35, 
    "forks": 19, 
    "open_issues": 35, 
    "watchers": 28, 
    "default_branch": "devel" 
    }] 

現在我希望提取像HTML_URL和叉子等,從這個項目。這是JSON。 幫幫我吧。

回答

0
private class HttpAsyncTask extends AsyncTask<String, Void, Object> { 
     @Override 
     protected Object doInBackground(String... urls) { 
      JSONParser jParser = new JSONParser(); 
      Object object = jParser.getJsonObject(urls[0]); 
      return object; 
     } 
     // onPostExecute displays the results of the AsyncTask. 
      @Override 
     public void onPostExecute(Object result){ 
     JSONObject jsonObject = (JSONObject) result; 
     JSONArray jsonArray = jsonObject.getJSONArray("data"); 
     for(int i=0;i<jsonArray.length;i++){ 
     System.out.println(jsObject.getString("id")); 

     } 
     System.out.println(jsObject.getString("forks_count")); 
     } 

    } 

,並採取一個多類JSONParser 然後粘貼下面的代碼

public class JSONParser { 
     static InputStream is = null; 
       static JSONObject jObj = null; 
       static String json = ""; 

       public JSONParser() { 
       } 

       /** 
       * This method is used to parse the Url by taking the url as parameter 
       * 
       * @param url 
       * @return 
       */ 
       public Object getJsonObject(String url) { 
        try { 
         DefaultHttpClient httpClient = new DefaultHttpClient(); 
         HttpGet httpGet = new HttpGet(url); 

         HttpParams httpParams = new BasicHttpParams(); 
         HttpConnectionParams.setStaleCheckingEnabled(httpParams, false); 
         HttpConnectionParams.setConnectionTimeout(httpParams, 15000); 
         HttpConnectionParams.setSoTimeout(httpParams, 15000); 
         httpGet.setParams(httpParams); 
         HttpResponse httpResponse = httpClient.execute(httpGet); 
         StatusLine statusLine = httpResponse.getStatusLine(); 
         if (statusLine.getStatusCode() == HttpStatus.SC_OK) { 
          HttpEntity httpEntity = httpResponse.getEntity(); 
          json = EntityUtils.toString(httpEntity); 
          try { 
           jObj = new JSONObject(json); 
          } catch (JSONException e) { 
           Log.e("JSON Parser", "Error parsing data " + e.toString()); 
          } 
          if (json.startsWith("[")) { 
           // We have a JSONArray 
           try { 
            jObj = new JSONObject(); 
            jObj.put("data", new JSONArray(json)); 
           } catch (JSONException e) { 
            Log.d("JSON Parser", 
              "Error parsing JSONArray " + e.toString()); 
           } 
           return jObj; 
          } 
          // return JSON String 
          return jObj; 
         } 
        } catch (UnsupportedEncodingException e) { 
         e.printStackTrace(); 
         return new String("Please check the connection"); 
        } catch (ClientProtocolException e) { 
         e.printStackTrace(); 
         return new String("Please check the connection"); 
        } catch (IOException e) { 
         e.printStackTrace(); 
         return new String("Please check the connection"); 
        } 
        return new String("Please check the connection"); 
       } 
      } 
+0

一些疑慮。我在哪裏指定我想要提取的字段。 – xyzzyspoon

+0

如何打印輸出? – xyzzyspoon

+0

在onPostExecute() –