Android 解析後臺返回為Json資料的簡單例子!!!
阿新 • • 發佈:2019-02-01
大家好,今天給大家分享下Android解析Json的例子,我這裡自己安裝了Tomcat,讓自己電腦充當下伺服器,最重要的是,返回結果自己可以隨便修改。
首先看下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封裝的工具類.
- */
- publicclass JSONUtil {
- privatestaticfinal String TAG = "JSONUtil";
- /**
- * 獲取json內容
- * @param url
- * @return JSONArray
- * @throws JSONException
- * @throws ConnectionException
- */
- publicstatic JSONObject getJSON(String url) throws JSONException, Exception {
- returnnew JSONObject(getRequest(url));
- }
- /**
- * 向api傳送get請求,返回從後臺取得的資訊。
- *
- * @param url
- * @return String
- */
- protectedstatic String getRequest(String url) throws Exception {
- return getRequest(url, new DefaultHttpClient(new BasicHttpParams()));
- }
- /**
- * 向api傳送get請求,返回從後臺取得的資訊。
- *
- * @param url
- * @param client
- * @return String
- */
- protectedstatic 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());
- thrownew Exception(e);
- } finally {
- getMethod.abort();
- }
- return result;
- }
- /**
- * 處理httpResponse資訊,返回String
- *
- * @param httpEntity
- * @return String
- */
- protectedstatic 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[] = newchar[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;
- publicclass JSONDemoActivity extends Activity {
- /**
- * 訪問的後臺地址,這裡訪問本地的不能用127.0.0.1應該用10.0.2.2
- */
- privatestaticfinal String BASE_URL = "http://10.0.2.2:8080/index2.jsp";
- private TextView mStudentTextView;
- private TextView mClassTextView;
- @Override
- publicvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- setupViews();
- }
- /**
- * 初始化
- */
- privatevoid 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程式碼如下:
- <?xmlversion="1.0"encoding="utf-8"?>
- <LinearLayoutxmlns: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中新增訪問網路許可權:
- <?xmlversion="1.0"encoding="utf-8"?>
- <manifestxmlns:android="http://schemas.android.com/apk/res/android"
- package="com.tutor.jsondemo"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-permissionandroid: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>
- <actionandroid:name="android.intent.action.MAIN"/>
- <categoryandroid:name="android.intent.category.LAUNCHER"/>
- </intent-filter>
- </activity>
- </application>
- </manifest>
執行工程,效果如下: