2014-12-26 2 views
0

안녕하세요 여러분, JSON 값을 추출하는 데 도움이 필요합니다. 구문 분석을 시도했지만 결과가 나오지 않습니다.Json Help for HTTPGET 반품

Heres는 내 자바 코드 :

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")); 
     } 

    } 

다음 코드

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

몇 가지 의문은 다음 붙여 하나 개 더 클래스 JSONParser 을. 어디에서 추출하고 싶은 분야를 지정해야합니까? – xyzzyspoon

+0

어떻게 출력물을 출력합니까? – xyzzyspoon

+0

onPostExecute() –