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

Android JSON 解析常見錯誤排查:從 JSONObject 例外反推資料結構

編輯:Android 開發實例

JSON 是 JavaScript 對象符號的縮寫,如今已成為一門獨立的資料交換格式,也是 XML 最有力的替代方案。它比 XML 短、比 XML 好讀,解析時也不必處理標籤與屬性的區別。本文除了說明 Android 如何解析 JSON,也會針對實作時最常撞到的幾個例外,示範如何從錯誤訊息反推問題所在。

Android 的四個 JSON 類別

JSONArray 對應方括號構成的陣列、JSONObject 對應花括號構成的物件、JSONStringer 用於組出 JSON 字串、JSONTokenizer 負責底層切詞。解析 API 回應時,你幾乎只會用到前兩個。

先確認你要的欄位在哪一層

在 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 }
}

JSON 元素

JSON 文件包含許多組件,下表定義了它們各自的角色:

  • Array([]):方括號在一個 JSON 文件中代表陣列。
  • Objects({}):花括號代表物件。
  • Key:JSON 物件中包含一個鍵,這是一個字串;鍵/值對共同組成一個 JSON 物件。
  • Value:每個鍵的值,可能是字串、整數或 double 等。

JSON 解析

解析一個 JSON 物件時,我們會建立一個一流的 JSONObject 物件,並把包含 JSON 資料的字串指定給它。語法如下:

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

最後一步是解析。一個 JSON 文件由不同的物件、不同的鍵/值對組成,因此 JSONObject 為每種組成準備了單獨的函式。語法如下:

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

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

getJSONObject() 回傳 JSON 物件;getString() 則回傳指定鍵的字串值。

除此之外還有哪些方法

  • get(String name):只回傳值,但形式是 Object 型別。
  • getBoolean(String name):回傳該鍵指定的布林值。
  • getDouble(String name):回傳該鍵指定的 double 值。
  • getInt(String name):回傳該鍵指定的整數值。
  • getLong(String name):回傳該鍵指定的 long 值。
  • length():回傳這個物件中名稱/值對應關係的數量。
  • names():回傳一個包含此物件所有字串名稱的陣列。

三個最常出現的例外

JSONException: No value for xxx——鍵不存在。可能是 API 改了欄位名稱,或該城市查不到資料而回傳了錯誤格式。用 reader.has("main") 先判斷,或改用 optJSONObject() 會安全得多。

JSONException: Value "..." cannot be converted to JSONObject——你用 getJSONObject() 去取一個實際上是字串或陣列的值。此時應改呼叫 getString() 或 getJSONArray()。

JSONException: End of input at character 0——傳進建構子的字串是空的。這幾乎都是網路層的問題:請求失敗、回傳了 HTML 錯誤頁,或串流還沒讀完就關閉。解析前先檢查 HTTP 狀態碼與字串長度。

範例

這裡示範如何使用 JSONObject 類別,建立一個基本的天氣應用程式,讓使用者從天氣 API 解析 JSON 並顯示結果。可在實機或模擬器上試驗。

實作步驟

  1. 使用 Android Studio 建立 Android 應用程式並命名為 JSONParser;建立專案時確認 Target SDK 編譯在最新版本並使用較高層級的 API。
  2. 修改 src/MainActivity.java 加入必要程式碼。
  3. 修改 res/layout/activity_main.xml 加入對應的 XML 元件。
  4. 修改 res/values/string.xml 加入必要字串。
  5. 在 src/ 建立新的 Java 檔 HandleJSON.java,用來取得並解析資料。
  6. 修改 AndroidManifest.xml 加入上網權限。
  7. 執行應用程式,選擇執行中的 Android 裝置安裝並驗證結果。

主活動 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 = "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/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/textView1"
        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/strings.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>

執行驗證

試著執行修改後的 JSONParser 應用。把程式安裝到 AVD 並啟動它,若一切設定與程式都沒有問題,會顯示這樣的模擬器視窗:

JSONParser 應用程式啟動畫面

接下來要做的,是在位置欄位中輸入任何地點。以紐約為例,按下 Weather 按鈕後畫面如下:

輸入紐約後按下查詢鈕的畫面

按下 Weather 鈕時,應用程式會連上服務、請求需要的 JSON 檔並解析它。

最後兩個提醒

請注意這個服務回傳的溫度是開爾文,若想轉成更易於理解的格式,必須換算成攝氏度(減去 273.15)。另外,範例中的 while(obj.parsingComplete); 只是為了讓教學程式看起來同步;在真實專案裡它會佔滿 CPU 核心,請改用背景任務加回呼,或直接用 Gson、Moshi、 kotlinx.serialization 這類對應式解析器把 JSON 映射成資料類別,能省下大量手寫 getX() 的樣板與出錯機會。

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