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

Android JSON 解析實戰:從 API 回傳資料到畫面顯示

編輯:Android 開發實例

JSON 的全名是 JavaScript Object Notation(JavaScript 物件符號法),它是一種與程式語言無關的輕量級資料交換格式,因為語法簡潔、可讀性高,早已成為 XML 之外最主流的選擇。在 Android 開發中,幾乎所有需要與網路服務溝通的 App,都會收到伺服器回傳的 JSON 字串,因此學會解析 JSON,是必備的基本功。

Android SDK 內建四個與 JSON 相關的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。其中又以 JSONObject 與 JSONArray 最常使用。

動手之前,第一步永遠是「先看清楚你要的是什麼」。以下是一段典型的天氣 API 回應,我們真正感興趣的只有溫度:

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

JSON 的基本組成元素

在看程式碼之前,先認識 JSON 文件的四個構成要素:

  • 陣列 Array([]):以方括號包起來的有序集合,例如上面的 weather。
  • 物件 Object({}):以花括號包起來的鍵值結構,例如 sys 與 main。
  • 鍵 Key:物件中的名稱,一定是字串,例如 "temp"、"country"。
  • 值 Value:對應鍵的內容,可以是字串、整數、浮點數、布林值、陣列或另一個物件。

解析 JSON 的兩個步驟

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

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

第二步則是逐層往下取值。JSONObject 針對不同層級與型別提供了各自的方法,例如 getJSONObject() 取得下一層的物件,getString() 取得指定鍵的字串值:

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

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

除了這兩個,JSONObject 還提供了更細緻的取值方法,可以依欄位型別挑選最合適的一個:

  • get(String name):以 Object 型別回傳任意值。
  • getBoolean(String name):取得布林值。
  • getDouble(String name):取得 double 數值。
  • getInt(String name):取得整數。
  • getLong(String name):取得 long 數值。
  • length():回傳這個物件包含幾組鍵值對。
  • names():回傳包含所有鍵名稱的陣列。

完整範例:做一個天氣查詢 App

接下來我們把上面的觀念串起來,做一個可以輸入城市名稱、按下按鈕後向天氣 API 索取 JSON 並解析顯示的小應用。你可以在實機或模擬器上執行。

  • 步驟 1:用 Android Studio 建立專案,命名為 JSONParser,Target SDK 與 Compile With 請盡量對齊最新版本。
  • 步驟 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"
        android:textAppearance="?android:attr/textAppearanceMedium" />
    <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/country" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/textView1"
        android:layout_marginTop="68dp" android:text="@string/country" />
    <EditText android:id="@+id/editText2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/country" android:ems="10" />
    <TextView android:id="@+id/temperature" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/editText2"
        android:layout_marginTop="19dp" android:text="@string/temperature" />
    <EditText android:id="@+id/editText3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/temperature" android:ems="10" />
    <TextView android:id="@+id/humidity" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/editText3"
        android:layout_marginTop="21dp" android:text="@string/humidity" />
    <EditText android:id="@+id/editText4" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/humidity" android:ems="10" />
    <TextView android:id="@+id/pressure" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/editText4"
        android:layout_marginTop="21dp" android:text="@string/pressure" />
    <EditText android:id="@+id/editText5" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/pressure" android:ems="10" />
    <Button android:id="@+id/button1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_below="@+id/editText5"
        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="action_settings">Settings</string>
    <string name="hello_world">Hello world!</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>

最後別忘了在 AndroidManifest.xml 加上 INTERNET 權限,否則程式會在連線時直接丟出例外:

 <?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-sdk android:minSdkVersion="8" android:targetSdkVersion="17" />
    <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 裝到 AVD 或真機啟動,若一切設定正確,你會看到這樣的起始畫面:

在位置欄位輸入任一座城市,這裡以紐約為例,按下 Weather 按鈕:

按下按鈕後,App 會向天氣服務發出請求、取回 JSON 並解析,再把國家、溫度、濕度、氣壓分別填回四個欄位。

小提醒:這個 API 回傳的溫度單位是 Kelvin(克氏),304.15 K 看起來很嚇人,其實只是約 31 度。若要顯示一般人熟悉的攝氏度,記得做個轉換:攝氏 = 克氏 - 273.15。

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