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

在 Android 中解析 JSON 資料:語法、常用方法與實作範例

編輯:Android 開發實例

JSON 是當今 App 與後端溝通最常見的資料格式。它輕量、可讀、跨語言支援完善,早已取代 XML 成為多數 API 的預設選擇。本文整理 Android 解析 JSON 所需的語法與方法,並透過一個天氣查詢範例實際演練。

Android 內建的 JSON 工具

org.json 套件裡有四個類別,分工如下:

  • JSONObject:代表一個 JSON 物件,由鍵與值成對組成,是最核心的類別。
  • JSONArray:代表一組有序的值,對應中括號結構。
  • JSONStringer:用於組裝並輸出 JSON 字串。
  • JSONTokenizer:提供逐字解析 JSON 文本的能力。

解析前的準備:確認欄位路徑

拿到一段陌生的 JSON,第一件事是找出目標欄位的完整路徑。以下回應中,我們要的是 main.temp:

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

JSON 元素一覽

元素說明
Array([ ])中括號代表陣列,元素有順序,可用索引取值。
Object({ })大括號代表物件,由一或多組鍵值對構成。
Key物件中的鍵必為字串,與其值共同組成一個鍵值對。
Value值可以是字串、整數、浮點數、布林,或另一層物件/陣列。

解析語法

建立 JSONObject 並帶入 JSON 字串:

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

逐層取值:

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

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

若目標是陣列,改用 getJSONArray("weather") 取得 JSONArray,再以 getJSONObject(i) 搭配迴圈取出每一筆。

方法速查

方法說明
get(String name)回傳指定鍵的值,型別為 Object。
getBoolean(String name)回傳布林值。
getDouble(String name)回傳 double 值。
getInt(String name)回傳整數值。
getLong(String name)回傳 long 值。
length()回傳鍵值對數量。
names()回傳所有鍵名稱組成的陣列。

實作範例:天氣查詢

使用者輸入城市,按下按鈕後 App 連線天氣服務、下載 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 並確認輸出。

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 finalUrl = url1 + location.getText().toString();

        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());
    }
}

HandleJSON.java

package com.example.jsonparser;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

import org.json.JSONObject;

import android.annotation.SuppressLint;

public class HandleJSON {

    private String country = "country";
    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(InputStream is) {
        Scanner s = new Scanner(is).useDelimiter("A");
        return s.hasNext() ? s.next() : "";
    }
}

把連線放進獨立 Thread 是必要設計:Android 3.0 之後,主執行緒若進行網路 I/O 會直接拋出例外。而 while (obj.parsingComplete); 這種 busy waiting 僅為教學簡化,正式專案請改用回呼或較現代的背景任務機制。

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/textV8iew1"
        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/textV8iew1"
        android:layout_alignParentRight="true"
        android:ems="10" />

    <TextView android:id="@+id/textV8iew2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textV8iew1"
        android:layout_below="@+id/textV8iew1"
        android:layout_marginTop="68dp"
        android:text="@string/country"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView android:id="@+id/textV8iew3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textV8iew2"
        android:layout_marginTop="19dp"
        android:text="@string/temperature"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView android:id="@+id/textV8iew4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textV8iew3"
        android:layout_below="@+id/textV8iew3"
        android:layout_marginTop="32dp"
        android:text="@string/humidity"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <TextView android:id="@+id/textV8iew5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textV8iew4"
        android:layout_below="@+id/textV8iew4"
        android:layout_marginTop="21dp"
        android:text="@string/pressure"
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <EditText android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textV8iew3"
        android:layout_toRightOf="@+id/textV8iew3"
        android:ems="10" >
        <requestFocus />
    </EditText>

    <EditText android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textV8iew3"
        android:layout_alignBottom="@+id/textV8iew3"
        android:layout_alignLeft="@+id/editText2"
        android:ems="10" />

    <EditText android:id="@+id/editText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/textV8iew5"
        android:layout_alignLeft="@+id/editText1"
        android:ems="10" />

    <EditText android:id="@+id/editText5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textV8iew5"
        android:layout_alignBottom="@+id/textV8iew5"
        android:layout_alignRight="@+id/editText4"
        android:ems="10" />

    <Button android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText2"
        android:layout_below="@+id/editText1"
        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

<?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 安裝到模擬器並啟動,畫面如下:

JSONParser 應用程式初始畫面

在位置欄位輸入城市(此例為紐約),按下 Weather:

輸入城市名稱並按下 Weather 按鈕

按下按鈕後,App 會連線天氣服務取得 JSON 並解析,把結果填入畫面各欄位。

溫度單位別搞錯

天氣服務回傳的 temp 預設是開爾文(Kelvin),不是攝氏。若要轉成比較直覺的攝氏度,用「開爾文 − 273.15」即可;也可以在請求網址加上 units=metric 讓服務端直接回傳攝氏。這個小細節是許多天氣 App 早期版本被使用者抱怨「溫度數字怪怪的」的原因。

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