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();
            }
        }
    }
}
时间: 2024-08-10 13:52:03

Chapter 10 Networking/JSON Services的相关文章

零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」

原文:零元学Expression Blend 4 - Chapter 10 用实例了解布局容器系列-「StackPanel」 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的乖宝宝-「StackPanel」:及加码赠送「ScrollViewer」的运用. 本系列将教大家以实做案例认识Blend 4 的布局容器,此章介绍的布局容器是Blend 4 里的乖宝宝-「StackPanel」:及加码赠送「ScrollViewer」的运用. 就是要让不会的新手

Python Chapter 10: 列表 Part3

10.10 查找列表 )线性查找 线性查找顺序地将关键字key与列表中的每一个元素进行比较,直到找到某个匹配元素时返回其下标,亦或在找不到时返回-1.代码如下: # The function for finding a key in a list def linearSearch(lst, key): for i in range(len(lst)): if lst[i] == key: return i return -1 若关键字存在,线性查找在找到关键字前平均需要查找一半的元素,其运行时间

Cpp Chapter 10: Objects and Classes Part2

10.2.4 Using classes Following exapmle uses the class definition and implementation written in previous files: // usestok0.cpp -- the client program // compiler with stock00.cpp #include <iostream> #include "stock00.h" int main() { Stock s

【Android开发经验】比Gson解析速度快10倍!——Json解析神器Jackson使用介绍

转载请注明出处:http://blog.csdn.net/zhaokaiqiang1992 在前面的两篇文章中,我们介绍了Json数据格式和系统自带Json以及Google的Gson项目,如果能学会这些东西,基本能满足工作需求了.但是,程序员都有追求极致效率的嗜好,在满足了基本需求之后,我们会考虑能不能再优化一下效率呢?当然!今天这篇文章要介绍的,就是在数据量比较大的时候,比Gson的解析效率高近10倍的Json数据解析框架- -Jackson! 下面是一个大神关于几个常见的Json数据的解析速

Delphi 10.2 JSON与对象/结构体序列化性能提高100多倍

今天在盒子闲逛,无意中看到有人说XE7自带的Json对象序列化很慢,帖子在这里:http://bbs.2ccc.com/topic.asp?topicid=464378;经过测试的确如此.     但是 D10.2后,自带的 Json 做了优化,性能大大的提高了100多倍. 和其他json库对比了序列化和反序列化性能,JsonDataObjects 性能最好,但是只支持简单的对象,不支持结构体,QJson 则不支持动态数组,不支持 Attributes (RTTI),比如需要过滤某个字段,自带和

Thinking in Java from Chapter 10

From Thinking in Java 4th Edition 内部类 public class Parcel1 { class Contents { private int i = 11; public int value { return i;} } class Destination { private String label; Destination(String whereTo) { label = whereTo; } String readLabel() { return l

C++ chapter 10——模板

**模板的概念 函数模板 类模板 名空间** 一.模板的概念 C++的模板提供对逻辑结构相同的数据对象通用行为的定义.模板运算对象的类型不是实际的数据类型,而是一种参数化的类型. 一个带类型参数的函数称为函数模板,一个带类型参数的类称为类模板. 二.函数模板 1.函数模板的概念 函数模板的基本原理是通过数据类型的参数化,将一组算法相同但所处理数据类型不同的重载函数凝练成一个函数模板.编译时,再由编译器按照函数模板自动生成针对不同数据类型的重载函数定义代码. 使用函数模板.对于函数模板,数据类型本

BDA chapter 10

numerical integration, 数值积分.numerical integration refers to methods in which the integral over continuous function is evaluated by computing the value of the function at finite number of points. Numerical integration methods can be divided to simulat

Head first java chapter 10 数字与静态

注意,先输出静态定义,然后运行main,输出"in main",然后statictests继承自staticsuper,所以先实现staticsuper,然后再实现statictests.