Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android JSON 解析實戰:從回應中取出你要的那幾個欄位

編輯:Android 開發實例

JSON(JavaScript Object Notation)早已成為應用程式之間交換資料的通用語言。相較於 XML,它沒有大量冗餘的封閉標籤,結構輕量、可讀性高,行動裝置解析起來也更省電省資源。本文要談的就是:在 Android 上如何把一段 JSON 字串讀進來,並準確取出真正需要的資訊。

Android SDK 內建四個與 JSON 有關的類別:JSONObject、JSONArray、JSONStringer 與 JSONTokenizer。實務上最常打交道的是前兩個,分別負責「物件」與「陣列」;後兩者則偏向循序組出字串與逐段掃描。

開始寫程式之前,先把資料看清楚。以下是一段典型的天氣服務回應,而我們真正想拿的是溫度:

 {
  "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 },
  "weather": [ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ],
  "main": { "temp":304.15, "pressure":1009 }
}

JSON 的四個基本元素

項目說明
Array([)方括號代表陣列,元素之間以逗號分隔,通常放同一類的物件集合。
Object({)大括號代表物件,是 JSON 最外層常見的包裝形式。
Key物件中的鍵,一定是字串,例如 temp、pressure。鍵與值配對,構成一個物件。
Value鍵對應的值,可以是字串、整數、浮點數、布林值、null,也可以是另一層物件或陣列。

解析的兩個步驟

第一步是把整段文字塞進 JSONObject 的建構子,讓它變成可供查詢的結構:

String in;
JSONObject reader = new JSONObject(in);

第二步是逐層往下取值。JSON 通常是巢狀的,所以先用 getJSONObject 取得子物件,再用 getString 這類方法取出實際內容:

JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");

JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");

getJSONObject() 回傳指定鍵下的子物件,getString() 則回傳該鍵對應的字串值。除此之外,JSONObject 還準備了一整組取得器,依資料型別選擇即可:

方法說明
get(String name)直接回傳值,型別為 Object,需要自行轉型。
getBoolean(String name)取得布林值。
getDouble(String name)取得 double 數值。
getInt(String name)取得整數。
getLong(String name)取得 long 數值。
length()回傳這個物件中鍵值對的數量。
names()回傳包含所有鍵名稱的陣列。

實務上還有一點值得注意:etter 若鍵可能不存在,改用 optInt()、optString() 這類「選配版」方法會比 getXxx() 安全,後者在找不到鍵時會丟出例外。

完整範例:一個會查天氣的小程式

接下來把上述觀念組起來,做一個可以輸入城市名稱、按下按鈕就抓回國家、溫度、濕度與氣壓的應用。實際的 HTTP 端點在程式碼中使用的是天氣服務的公開 API。範例可在實機或模擬器上執行。

步驟做法
1用 Android Studio 建立專案,命名為 JSONParser;建立時把 Target SDK 與 Compile With 設為較新的 SDK 版本,才能使用較新的 API。
2在 src/MainActivity.java 補上界面邏輯與按鈕事件。
3編輯 res/layout/activity_main.xml,放入輸入框、文字標籤與按鈕。
4在 res/values/string.xml 加入所有會用到的字串資源。
5新增 src/HandleJSON.java,負責發請求並解析回傳的 JSON。
6在 AndroidManifest.xml 宣告網路權限。
7執行 App,選擇目標裝置,確認結果正確。

主活動的內容如下(src/com.yiibai.jsonparser/MainActivity.java):

 package com.example.jsonparser;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
    private String url1 = "https://api.openweathermap.org/data/2.5/weather?q=";
    private EditText location,country,temperature,humidity,pressure;
    private HandleJSON obj;
    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        location = (EditText)findViewById(R.id.editText1);
        country = (EditText)findViewById(R.id.editText2);
        temperature = (EditText)findViewById(R.id.editText3);
        humidity = (EditText)findViewById(R.id.editText4);
        pressure = (EditText)findViewById(R.id.editText5);
    }
    @Override public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void open(View view){
        String url = location.getText().toString();
        String finalUrl = url1 + url;
        country.setText(finalUrl);
        obj = new HandleJSON(finalUrl);
        obj.fetchJSON();
        while(obj.parsingComplete);
        country.setText(obj.getCountry());
        temperature.setText(obj.getTemperature());
        humidity.setText(obj.getHumidity());
        pressure.setText(obj.getPressure());
    }
} 

負責連線與解析的 src/com.yiibai.jsonparser/HandleJSON.java:

 package com.example.jsonparser;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import android.annotation.SuppressLint;
public class HandleJSON {
    private String country = "county";
    private String temperature = "temperature";
    private String humidity = "humidity";
    private String pressure = "pressure";
    private String urlString = null;
    public volatile boolean parsingComplete = true;
    public HandleJSON(String url){ this.urlString = url; }
    public String getCountry(){ return country; }
    public String getTemperature(){ return temperature; }
    public String getHumidity(){ return humidity; }
    public String getPressure(){ return pressure; }
    @SuppressLint("NewApi") public void readAndParseJSON(String in) {
        try {
            JSONObject reader = new JSONObject(in);
            JSONObject sys = reader.getJSONObject("sys");
            country = sys.getString("country");
            JSONObject main = reader.getJSONObject("main");
            temperature = main.getString("temp");
            pressure = main.getString("pressure");
            humidity = main.getString("humidity");
            parsingComplete = false;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void fetchJSON(){
        Thread thread = new Thread(new Runnable(){
            @Override public void run() {
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("GET");
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream stream = conn.getInputStream();
                    String data = convertStreamToString(stream);
                    readAndParseJSON(data);
                    stream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }
    static String convertStreamToString(java.io.InputStream is) {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("A");
        return s.hasNext() ? s.next() : "";
    }
} 

版面配置 res/layout/activity_main.xml:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView android:id="@+id/textView1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" android:layout_marginTop="15dp"
        android:text="@string/location" />
    <EditText android:id="@+id/editText1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignBottom="@+id/textView1"
        android:layout_alignParentRight="true" android:ems="10" />
    <TextView android:id="@+id/textView2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/textViedw1"
        android:layout_marginTop="68dp" android:text="@string/country" />
    <EditText android:id="@+id/editText2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <EditText android:id="@+id/editText3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <EditText android:id="@+id/editText4" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <EditText android:id="@+id/editText5" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <Button android:id="@+id/button1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:onClick="open"
        android:text="@string/weather" />
</RelativeLayout>

字串資源 res/values/string.xml:

 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">JSONParser</string>
    <string name="location">Location</string>
    <string name="country">Country:</string>
    <string name="temperature">Temperature:</string>
    <string name="humidity">Humidity:</string>
    <string name="pressure">Pressure:</string>
    <string name="weather">Weather</string>
</resources>

別忘了網路權限,否則請求會在執行期被丟 SecurityException。這是 AndroidManifest.xml:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.yiibai.jsonparser" android:versionCode="1" android:versionName="1.0" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <application android:allowBackup="true" android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" android:theme="@style/AppTheme" >
        <activity android:name="com.yiibai.jsonparser.MainActivity"
            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>

把 App 裝到模擬器上啟動,一切設定正確的話會看到這樣的畫面:

接著在位置欄位輸入任一座城市,這裡示範紐約,按下 weather 按鈕:

按下按鈕後,程式會向天氣服務發出請求、取回 JSON 並解析,最後把欄位填進畫面。需要留意的是,回傳的溫度單位是克氏(Kelvin),若要顯示成比較直覺的攝氏,記得減去 273.15。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved