1. 程式人生 > >Android 解析後臺返回為Json資料的簡單例子!!!

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

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

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

JSON的定義:

一種輕量級的資料交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術為其提供了完整的解決方案(有點類似於正則表示式 ,獲得了當今大部分語言的支援),從而可以在不同平臺間進行資料交換。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安裝:

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

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

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

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

新建一個Android工程JsonDemo.

工程目錄如下:


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

  1. package com.tutor.jsondemo;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4. import java.io.UnsupportedEncodingException;  
  5. import org.apache.http.HttpEntity;  
  6. import org.apache.http.HttpResponse;  
  7. import org.apache.http.client.methods.HttpGet;  
  8. import org.apache.http.impl.client.DefaultHttpClient;  
  9. import org.apache.http.params.BasicHttpParams;  
  10. import org.apache.http.protocol.HTTP;  
  11. import org.json.JSONException;  
  12. import org.json.JSONObject;  
  13. import android.util.Log;  
  14. /** 
  15.  * @author frankiewei. 
  16.  * Json封裝的工具類. 
  17.  */
  18. publicclass JSONUtil {  
  19.     privatestaticfinal String TAG = "JSONUtil";  
  20.     /** 
  21.      * 獲取json內容 
  22.      * @param  url 
  23.      * @return JSONArray 
  24.      * @throws JSONException  
  25.      * @throws ConnectionException  
  26.      */
  27.     publicstatic JSONObject getJSON(String url) throws JSONException, Exception {  
  28.         returnnew JSONObject(getRequest(url));  
  29.     }  
  30.     /** 
  31.      * 向api傳送get請求,返回從後臺取得的資訊。 
  32.      *  
  33.      * @param url 
  34.      * @return String 
  35.      */
  36.     protectedstatic String getRequest(String url) throws Exception {  
  37.         return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));  
  38.     }  
  39.     /** 
  40.      * 向api傳送get請求,返回從後臺取得的資訊。 
  41.      *  
  42.      * @param url 
  43.      * @param client 
  44.      * @return String 
  45.      */
  46.     protectedstatic String getRequest(String url, DefaultHttpClient client) throws Exception {  
  47.         String result = null;  
  48.         int statusCode = 0;  
  49.         HttpGet getMethod = new HttpGet(url);  
  50.         Log.d(TAG, "do the getRequest,url="+url+"");  
  51.         try {  
  52.             //getMethod.setHeader("User-Agent", USER_AGENT);
  53.             HttpResponse httpResponse = client.execute(getMethod);  
  54.             //statusCode == 200 正常
  55.             statusCode = httpResponse.getStatusLine().getStatusCode();  
  56.             Log.d(TAG, "statuscode = "+statusCode);  
  57.             //處理返回的httpResponse資訊
  58.             result = retrieveInputStream(httpResponse.getEntity());  
  59.         } catch (Exception e) {  
  60.             Log.e(TAG, e.getMessage());  
  61.             thrownew Exception(e);  
  62.         } finally {  
  63.             getMethod.abort();  
  64.         }  
  65.         return result;  
  66.     }  
  67.     /** 
  68.      * 處理httpResponse資訊,返回String 
  69.      *  
  70.      * @param httpEntity 
  71.      * @return String 
  72.      */
  73.     protectedstatic String retrieveInputStream(HttpEntity httpEntity) {  
  74.         int length = (int) httpEntity.getContentLength();         
  75.         //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.
  76.         //length==-1,下面這句報錯,println needs a message
  77.         if (length < 0) length = 10000;  
  78.         StringBuffer stringBuffer = new StringBuffer(length);  
  79.         try {  
  80.             InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8);  
  81.             char buffer[] = newchar[length];  
  82.             int count;  
  83.             while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) {  
  84.                 stringBuffer.append(buffer, 0, count);  
  85.             }  
  86.         } catch (UnsupportedEncodingException e) {  
  87.             Log.e(TAG, e.getMessage());  
  88.         } catch (IllegalStateException e) {  
  89.             Log.e(TAG, e.getMessage());  
  90.         } catch (IOException e) {  
  91.             Log.e(TAG, e.getMessage());  
  92.         }  
  93.         return stringBuffer.toString();  
  94.     }  
  95. }  
編寫主Activity程式碼JSONDemoActivity,程式碼如下:

  1. package com.tutor.jsondemo;  
  2. import org.json.JSONArray;  
  3. import org.json.JSONException;  
  4. import org.json.JSONObject;  
  5. import android.app.Activity;  
  6. import android.os.Bundle;  
  7. import android.widget.TextView;  
  8. publicclass JSONDemoActivity extends Activity {  
  9.     /** 
  10.      * 訪問的後臺地址,這裡訪問本地的不能用127.0.0.1應該用10.0.2.2 
  11.      */
  12.     privatestaticfinal String BASE_URL = "http://10.0.2.2:8080/index2.jsp";  
  13.     private TextView mStudentTextView;  
  14.     private TextView mClassTextView;  
  15.     @Override
  16.     publicvoid onCreate(Bundle savedInstanceState) {  
  17.         super.onCreate(savedInstanceState);  
  18.         setContentView(R.layout.main);  
  19.         setupViews();  
  20.     }  
  21.     /** 
  22.      * 初始化 
  23.      */
  24.     privatevoid setupViews(){  
  25.         mStudentTextView = (TextView)findViewById(R.id.student);  
  26.         mClassTextView = (TextView)findViewById(R.id.classes);  
  27.         try {  
  28.             //獲取後臺返回的Json物件
  29.             JSONObject mJsonObject = JSONUtil.getJSON(BASE_URL);  
  30.             //獲得學生陣列
  31.             JSONArray mJsonArray = mJsonObject.getJSONArray("students");  
  32.             //獲取第一個學生
  33.             JSONObject firstStudent = mJsonArray.getJSONObject(0);  
  34.             //獲取班級
  35.             String classes = mJsonObject.getString("class");  
  36.             String studentInfo = classes + "共有 " + mJsonArray.length() + " 個學生."
  37.                                  + "第一個學生姓名: " + firstStudent.getString("name")  
  38.                                  + " 年齡: " + firstStudent.getInt("age");  
  39.             mStudentTextView.setText(studentInfo);  
  40.             mClassTextView.setText("班級: " + classes);  
  41.         } catch (JSONException e) {  
  42.             e.printStackTrace();  
  43.         } catch (Exception e) {  
  44.             e.printStackTrace();  
  45.         }  
  46.     }  
  47. }  

這裡用到的佈局檔案main.xml程式碼如下:

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3.     android:layout_width="fill_parent"
  4.     android:layout_height="fill_parent"
  5.     android:orientation="vertical">
  6.     <TextView
  7.         android:id="@+id/student"
  8.         android:layout_width="fill_parent"
  9.         android:layout_height="wrap_content"
  10.         android:text="@string/hello"/>
  11.     <TextView
  12.         android:id="@+id/classes"
  13.         android:layout_width="fill_parent"
  14.         android:layout_height="wrap_content"
  15.         />
  16. </LinearLayout>

最後要在AndroidMainfest.xml中新增訪問網路許可權:
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <manifestxmlns:android="http://schemas.android.com/apk/res/android"
  3.     package="com.tutor.jsondemo"
  4.     android:versionCode="1"
  5.     android:versionName="1.0">
  6.     <uses-permissionandroid:name="android.permission.INTERNET"></uses-permission>
  7.     <application
  8.         android:icon="@drawable/ic_launcher"
  9.         android:label="@string/app_name">
  10.         <activity
  11.             android:name=".JSONDemoActivity"
  12.             android:label="@string/app_name">
  13.             <intent-filter>
  14.                 <actionandroid:name="android.intent.action.MAIN"/>
  15.                 <categoryandroid:name="android.intent.category.LAUNCHER"/>
  16.             </intent-filter>
  17.         </activity>
  18.     </application>
  19. </manifest>

執行工程,效果如下: