Json帮助HTTPGET返回

时间:2014-12-26 05:00:21

标签: android json github

嘿伙计我需要帮助来提取JSON值。我试过解析但结果没有出来。

继承我的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。 帮助我们。

1 个答案:

答案 0 :(得分: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");
                }
            }