Chapter 10 Networking/JSON Services

來源:互聯網
上載者:User

標籤:android   style   blog   http   io   ar   color   os   sp   

<1>JSON Service

  In the previous section, you learned how to consume XML web services by using HTTP to connect to the web server and then obtain the

    results in XML. You also learned how to use DOM to parse the result of the XML document.

  However, manipulating XML documents is a computationally expensive operation for mobile devices, for the following reasons:

  <i> XML documents are lengthy.

    They use tags to embed information, and the size of an XML document can get very big pretty quickly. A large XML document means

      that your device has to use more bandwidth to download it, which translates into higher cost.

  <ii> XML documents are more difficult to process.

    As shown earlier, you have to use DOM to traverse the tree in order to locate the information you want. In addition, DOM itself has

      to build the entire document in memory as a tree structure before you can traverse it. This is both memory and CPU intensive.

  JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write

    It is also easy for machines to parse and generate.

[    {        “appeId”:”1”,        “survId”:”1”,       “location”:””,     “surveyDate”:”2008-03 14”,     “surveyTime”:”12:19:47”,     “inputUserId”:”1”,     “inputTime”:”2008-03-14 12:21:51”,     “modifyTime”:”0000-00-00 00:00:00”   },    {     “appeId”:”2”,     “survId”:”32”,     “location”:””,     “surveyDate”:”2008-03-14”,     “surveyTime”:”22:43:09”,     “inputUserId”:”32”,     “inputTime”:”2008-03-14 22:43:37”,     “modifyTime”:”0000-00-00 00:00:00”   },   {     “appeId”:”3”,     “survId”:”32”,     “location”:””,     “surveyDate”:”2008-03-15”,     “surveyTime”:”07:59:33”,     “inputUserId”:”32”,     “inputTime”:”2008-03-15 08:00:44”,     “modifyTime”:”0000-00-00 00:00:00”   }] 

  information is represented as a collection of key/value pairs. each key/value pair is grouped into an ordered list of objects. 

  Unlike XML, there are no lengthy tag names, only brackets and braces.

package mirror.android.jsonservice;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.StatusLine;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.widget.Toast;public class JSONActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_json);                new ReadJSONFeedTask().execute("https://twitter.com/statuses/user_timeline/weimenglee.json");    }        public String ReadJSONFeed(String URL){                StringBuilder stringBuilder = new StringBuilder();        HttpClient client = new DefaultHttpClient();        HttpGet httpGet = new HttpGet(URL);                try {            HttpResponse response = client.execute(httpGet);            StatusLine statusLine = response.getStatusLine();            int statusCode = statusLine.getStatusCode();                        if(statusCode == 200){                HttpEntity entity = response.getEntity();                InputStream in = entity.getContent();                                BufferedReader reader = new BufferedReader(new InputStreamReader(in));                String line;                                while((line = reader.readLine()) != null){                    stringBuilder.append(line);                }            }            else{                Log.e("JSON", "Failed to download file");            }        } catch (Exception e) {            e.printStackTrace();        }        return stringBuilder.toString();    }        private class ReadJSONFeedTask extends AsyncTask<String, Void, String>{        @Override        protected String doInBackground(String... urls) {            return ReadJSONFeed(urls[0]);        }        @Override        protected void onPostExecute(String result) {            try {                JSONArray jsonArray = new JSONArray(result);                Log.i("JSON", "Number of surveys in feed:" + jsonArray.length());                                for (int i = 0; i < jsonArray.length(); i++) {                    JSONObject jsonObject = jsonArray.getJSONObject(i);                    Toast.makeText(getApplication(),                                 jsonObject.getString("text") + " - " + jsonObject.getString("created_at"),                                Toast.LENGTH_SHORT).show();                }            } catch (JSONException e) {                e.printStackTrace();            }        }    }}

 

Chapter 10 Networking/JSON Services

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.