Thingspeak json Android Parse

时间:2016-10-05 18:30:09

标签: android json

我正在研究一些事情。我有一个json链接。http://api.thingspeak.com/channels/145827/feed/last.json我怎样才能为android解析这个。

1 个答案:

答案 0 :(得分:0)

获取JSON的代码,这很好。

获取JSON的类

    import android.util.Log;        
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.util.EntityUtils;
    import org.json.JSONArray;
    import org.json.JSONException;        
    import java.io.IOException;

    public class ApiConnector { //Connector class
        public JSONArray GetYourJson()
        {
            // URL for getting the json
            String url = "http://api.thingspeak.com/channels/145827/feed/last.json";

            // Get HttpResponse Object from url.
            // Get HttpEntity from Http Response Object
            HttpEntity httpEntity = null;

            try
            {
                DefaultHttpClient httpClient = new DefaultHttpClient();  // Default HttpClient
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);

                httpEntity = httpResponse.getEntity();

            } catch (ClientProtocolException e) {

                // Signals error in http protocol
                e.printStackTrace();

                //Log Errors Here

            } catch (IOException e) {
                e.printStackTrace();
            }


            // Convert HttpEntity into JSON Array
            JSONArray jsonArray = null;

            if (httpEntity != null) {
                try {
                    String entityResponse = EntityUtils.toString(httpEntity);

                    Log.e("Entity Response  : ", entityResponse);

                    jsonArray = new JSONArray(entityResponse);

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return jsonArray;
        }

    }

AsyckTaks运行ApiConnector,这样做你的UI不会冻结。

    private class GetYourJsonTask extends AsyncTask<ApiConnector,Long,JSONArray>
    {
        @Override
        protected JSONArray doInBackground(ApiConnector... params) {

            // it is executed on Background thread

            return params[0].GetYourJson();
        }
        @Override
        protected void onPostExecute(JSONArray jsonArray) {
            //TODO: Do what you want with your json here
        }
    }

然后从UI中调用它

new GetYourJsonTask().execute(new ApiConnector());