Chapter 10 Networking/JSON Services

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

 

转载于:https://www.cnblogs.com/iMirror/p/4117266.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值