Android解析Json的例子,
首先看下Json的定義,以及它和XML的比較:
JSON的定義:
一種輕量級的數據交換格式,具有良好的可讀和便於快速編寫的特性。業內主流技術爲其提供了完整的解決方案(有點類似於正則表達式 ,獲得了當今大部分語言的支持),從而可以在不同平臺間進行數據交換。JSON採用兼容性很高的文本格式,同時也具備類似於C語言體系的行爲。 – Json.org
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,用記事本或者什麼的,編輯內容如下:
- {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();
- }
- }
- 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>
運行工程,效果如下: