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

Android 如何解析 JSON?從 JSONObject 到天氣查詢 App 的完整示範

編輯:Android 開發實例

行動裝置上的 App 要拿到伺服器的資料,回傳格式十之八九是 JSON。JSON 的全名是 JavaScript Object Notation,它與程式語言無關、純文字、結構簡單,因此被廣泛用來取代 XML 成為資料交換的主流格式。

本文要談的是 Android 端怎麼把 JSON 字串拆解成可用的資料,並透過一個實際的天氣查詢範例把整個流程串起來。

先認識四個角色

Android 內建的 org.json 套件提供了四個類別:

  • JSONObject:對應一個以鍵值對組成的 JSON 物件,是最常使用的。
  • JSONArray:對應有序的值集合,也就是中括號包起來的部分。
  • JSONStringer:反過來用,負責組裝出 JSON 字串。
  • JSONTokenizer:逐字解析 JSON 文本的低階工具。

看過資料再動手

解析前一定要先確認欄位的層級關係。以下是一段天氣 API 的回應,我們鎖定的目標是 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對應的值,可以是字串、整數、浮點數、布林,甚至是另一層物件或陣列。

解析的標準寫法

先把整段 JSON 文字交給 JSONObject 建構子,它就會完成最外層物件的解析:

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");

getJSONObject() 取得子物件,getString() 取得字串值。若某一層其實是陣列,就改用 getJSONArray(),再用迴圈搭配 arr.getJSONObject(i) 逐一取出。

JSONObject 的方法清單

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

動手做:天氣查詢 App

範例會做出一個畫面:輸入城市名稱,按下 Weather,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,加上 INTERNET 權限。
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 起禁止在主執行緒進行網路連線。volatile 修飾的 parsingComplete 旗標則讓主執行緒能得知解析何時完成;正式專案更建議改用回呼介面或非同步任務 API,避免 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/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/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、解析後把結果填進各個欄位。

兩個實務提醒

第一,天氣 API 回傳的溫度預設是開爾文,若要顯示攝氏,減去 273.15 即可,或在請求網址加上 units=metric。第二,解析外部資料時請務必包在 try-catch 裡,並優先考慮 optString()、optJSONObject() 這類容錯方法——線上服務的欄位隨時可能異動,寫死 getString() 往往就是閃退的來源。

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