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

Android JSON 解析實戰:用 JSONObject 把天氣資料變成 App 畫面

編輯:Android 開發實例

JSON(JavaScript Object Notation)早已是行動裝置與伺服器溝通的首選格式。相較於 XML,它沒有冗長的標籤、沒有命名空間的困擾,解析時也不必來回搬動節點指標,因此幾乎所有開放平臺都改用 JSON 回傳資料。本文從最基礎的結構辨識講起,一路做到一個能查詢城市天氣的 Android 小程式。

Android 內建的四個 JSON 工具類別

Android 自 1.5 起就內含 org.json 套件,四個類別各有分工:

  • JSONObject:對應一組以花括號包住的鍵值集合,日常開發使用率最高。
  • JSONArray:對應以方括號包住的序列,元素可以是物件、陣列或純量。
  • JSONStringer:以串流方式組出合法 JSON 字串,適合動態產生回應內容。
  • JSONTokener:最底層的詞法分析器,負責把字串切成 token。

第一步:先看清資料的長相

寫任何一行解析程式之前,請先把 API 回傳的內容攤開來看。以下是一段典型的天氣資料,我們真正想要的是 main 裡的溫度:

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

JSON 的四個基本元素

  • 陣列 []:同質資料的清單。上例的 weather 就是陣列,即使只有一筆,也必須用索引取值。
  • 物件 {}:由多組鍵值交所構成,例如 sys 與 main。
  • 鍵 Key:必然是字串,且要用雙引號包住,例如 "country"。
  • 值 Value:可以是字串、整數、浮點數、布林、null,也可以是另一個物件或陣列。

第二步:解析的兩個動作

先把整段文字交給 JSONObject 建構子,讓它完成詞法與語法分析:

String in;                                   // 自網路讀回來的原始字串
JSONObject reader = new JSONObject(in);

接著按層級往下走。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 / getDouble / getInt / getLong(String name):依指定型別取值,型別不符會丟出例外。
  • length():回傳這個物件共有幾組鍵值對。
  • names():回傳包含所有鍵名稱的陣列。
  • optString / optInt 系列:鍵不存在時回傳預設值而不拋例外。面對不可信的外部資料時,這組方法比 getX() 安全得多。

完整範例:簡易天氣查詢

這個範例讓使用者輸入城市名稱,程式呼叫天氣服務取得 JSON,解析後把國家、溫度、濕度、氣壓填進四個欄位。實機與模擬器都能執行。

實作步驟

  1. 用 Android Studio 建立專案並命名為 JSONParser,Target SDK 與 Compile With 皆選最新版本。
  2. 修改 src/MainActivity.java,加入控制項與按鈕事件。
  3. 調整 res/layout/activity_main.xml 的版面。
  4. 在 res/values/strings.xml 補上字串資源。
  5. 新增 src/HandleJSON.java,負責在背景執行緒抓取並解析資料。
  6. 在 AndroidManifest.xml 加上 INTERNET 權限。
  7. 編譯安裝,實測驗證。

主活動程式,src/com.example.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.example.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 = "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(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/textV8iew2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="68dp"
        android:text="@string/country" />

    <TextView android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="19dp"
        android:text="@string/temperature" />

    <TextView android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView3"
        android:layout_below="@+id/textView3"
        android:layout_marginTop="32dp"
        android:text="@string/humidity" />

    <TextView android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/textView4"
        android:layout_marginTop="21dp"
        android:text="@string/pressure" />

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

    <EditText android:id="@+id/editText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textView3"
        android:layout_alignBottom="@+id/textView3"
        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/textView5"
        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/textView5"
        android:layout_alignBottom="@+id/textView5"
        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/strings.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>

別忘了網路權限,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 裝到 AVD 或真機上啟動,若環境設定無誤會看到這樣的初始畫面:

JSONParser 應用程式啟動畫面

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

輸入城市後查詢天氣的結果畫面

按下按鈕的瞬間,程式會連上服務端、下載 JSON、逐層解析,再把欄位填回畫面。

兩個實務上必須留意的細節

第一,這個服務回傳的溫度是開爾文。若要轉成攝氏,用 攝氏 = 開爾文 − 273.15 即可;304.15 K 大約是 31 °C。

第二,Android 3.0 之後主執行緒禁止發起網路連線,直接這樣寫會收到 NetworkOnMainThreadException。教學用的範例靠 while(obj.parsingComplete); 這種忙等來同步,真實專案請改用背景執行緒搭配回呼、Coroutine,或直接用 OkHttp、Retrofit 這類成熟套件,並記得把端點換成 HTTPS。

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