Android 解析後台返回為Json資料的簡單例子

來源:互聯網
上載者:User

大家好,今天給大家分享下Android解析Json的例子,我這裡自己安裝了Tomcat,讓自己電腦充當下伺服器,最重要的是,返回結果自己可以隨便修改。

首先看下Json的定義,以及它和XML的比較:

JSON的定義:

一種輕量級的資料交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術為其提供了完整的解決方案(有點類似於Regex ,獲得了當今大部分語言的支援),從而可以在不同平台間進行資料交換。JSON採用相容性很高的文字格式設定,同時也具備類似於C語言體系的行為。 – Json.org

JSON Vs XML

1.JSON和XML的資料可讀性基本相同
2.JSON和XML同樣擁有豐富的解析手段
3.JSON相對於XML來講,資料的體積小
4.JSON與JavaScript的互動更加方便
5.JSON對資料的描述性比XML較差
6.JSON的速度要遠遠快於XML.

Tomcat安裝:

Tomcathttp://tomcat.apache.org/ 下載後安裝,如果成功,啟動Tomcat,然後在瀏覽器裡輸入:http://localhost:8080/index.jsp,會有個Tomcat首頁介面,

我們在Tomcat安裝目錄下webapps\ROOT下找到index.jsp,然後建立一個index2.jsp,用記事本或者什麼的,編輯內容如下:

{students:[{name:'魏祝林',age:25},{name:'阿魏',age:26}],class:'三年二班'}

然後我們在瀏覽器裡輸入:http://localhost:8080/index2.jsp返回的結果如下(這就類比出後台返回的資料了):

建立一個Android工程JsonDemo.

工程目錄如下:

這裡我封裝了一個JSONUtil工具類,代碼如下:

package com.tutor.jsondemo;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.BasicHttpParams;import org.apache.http.protocol.HTTP;import org.json.JSONException;import org.json.JSONObject;import android.util.Log;/** * @author frankiewei. * Json封裝的工具類. */public class JSONUtil {        private static final String TAG = "JSONUtil";        /**     * 擷取json內容     * @param  url     * @return JSONArray     * @throws JSONException      * @throws ConnectionException      */    public static JSONObject getJSON(String url) throws JSONException, Exception {                return new JSONObject(getRequest(url));    }        /**     * 向api發送get請求,返回從後台取得的資訊。     *      * @param url     * @return String     */    protected static String getRequest(String url) throws Exception {        return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));    }        /**     * 向api發送get請求,返回從後台取得的資訊。     *      * @param url     * @param client     * @return String     */    protected static String getRequest(String url, DefaultHttpClient client) throws Exception {        String result = null;        int statusCode = 0;        HttpGet getMethod = new HttpGet(url);        Log.d(TAG, "do the getRequest,url="+url+"");        try {            //getMethod.setHeader("User-Agent", USER_AGENT);            HttpResponse httpResponse = client.execute(getMethod);            //statusCode == 200 正常            statusCode = httpResponse.getStatusLine().getStatusCode();            Log.d(TAG, "statuscode = "+statusCode);            //處理返回的httpResponse資訊            result = retrieveInputStream(httpResponse.getEntity());        } catch (Exception e) {            Log.e(TAG, e.getMessage());            throw new Exception(e);        } finally {            getMethod.abort();        }        return result;    }        /**     * 處理httpResponse資訊,返回String     *      * @param httpEntity     * @return String     */    protected static String retrieveInputStream(HttpEntity httpEntity) {                        int length = (int) httpEntity.getContentLength();                //the number of bytes of the content, or a negative number if unknown. If the content length is known but exceeds Long.MAX_VALUE, a negative number is returned.        //length==-1,下面這句報錯,println needs a message        if (length < 0) length = 10000;        StringBuffer stringBuffer = new StringBuffer(length);        try {            InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);            char buffer[] = new char[length];            int count;            while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {                stringBuffer.append(buffer, 0, count);            }        } catch (UnsupportedEncodingException e) {            Log.e(TAG, e.getMessage());        } catch (IllegalStateException e) {            Log.e(TAG, e.getMessage());        } catch (IOException e) {            Log.e(TAG, e.getMessage());        }        return stringBuffer.toString();    }}

編寫主Activity代碼JSONDemoActivity,代碼如下:

package com.tutor.jsondemo;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.app.Activity;import android.os.Bundle;import android.widget.TextView;public class JSONDemoActivity extends Activity {        /**     * 訪問的後台地址,這裡訪問本地的不能用127.0.0.1應該用10.0.2.2     */    private static final String BASE_URL = "http://10.0.2.2:8080/index2.jsp";        private TextView mStudentTextView;        private TextView mClassTextView;            @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                setupViews();    }        /**     * 初始化     */    private void setupViews(){        mStudentTextView = (TextView)findViewById(R.id.student);        mClassTextView = (TextView)findViewById(R.id.classes);                try {            //擷取後台返回的Json對象            JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);                        //獲得學生數組            JSONArray mJsonArray = mJsonObject.getJSONArray("students");            //擷取第一個學生            JSONObject firstStudent = mJsonArray.getJSONObject(0);            //擷取班級            String classes = mJsonObject.getString("class");                                                String studentInfo = classes + "共有 " + mJsonArray.length() + " 個學生."                                 + "第一個學生姓名: " + firstStudent.getString("name")                                 + " 年齡: " + firstStudent.getInt("age");                        mStudentTextView.setText(studentInfo);                        mClassTextView.setText("班級: " + classes);        } catch (JSONException e) {            e.printStackTrace();        } catch (Exception e) {            e.printStackTrace();        }    }        }

這裡用到的布局檔案main.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/student"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" />        <TextView         android:id="@+id/classes"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        /></LinearLayout>

最後要在AndroidMainfest.xml中添加訪問網路許可權:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.tutor.jsondemo"    android:versionCode="1"    android:versionName="1.0" >        <uses-permission android:name="android.permission.INTERNET"></uses-permission>    <application        android:icon="@drawable/ic_launcher"        android:label="@string/app_name" >        <activity            android:name=".JSONDemoActivity"            android:label="@string/app_name" >            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

 

運行工程,效果如下:

 

轉:http://blog.csdn.net/android_tutor/article/details/7466620

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.