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

Android 如何解析 JSON:從 API 回傳資料中取出欄位值

編輯:Android 開發實例

JSON 的全名是 JavaScript Object Notation,是一種與程式語言無關的資料交換格式。相較於 XML,它沒有冗長的標籤,結構清楚、體積更小,解析速度也更快,因此成為行動應用對接 RESTful API 的首選。

Android 內建四個 JSON 相關類別:JSONArray、JSONObject、JSONStringer、JSONTokenizer。日常開發中,讀取物件用 JSONObject、讀取陣列用 JSONArray,這兩者已足以應付絕大多數情境。

解析工作通常從「確認你要什麼」開始。以下面這份資料為例,我們想知道的是溫度:

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

看懂 JSON 的結構

元件說明
Array []中括號表示陣列,元素以逗號分隔
Object {}大括號表示物件
Key物件中的鍵,必須是字串,並以雙引號包住
Value鍵對應的值,可以是字串、數字、布林、陣列或另一個物件

解析的兩個階段

第一階段是把整段文字包成 JSONObject:

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() 往下鑽,遇到純量值就用 getString() 取出。

此外,JSONObject 還有下列取值與查詢方法:

方法說明
get(String name)回傳值本身,維持原始型別
getBoolean(String name)取得指定鍵的布林值
getDouble(String name)取得指定鍵的 double 值
getInt(String name)取得指定鍵的整數值
getLong(String name)取得指定鍵的 long 值
length()回傳這個物件所含鍵值對的數量
names()回傳包含所有鍵名的字串陣列

實作範例:抓取並顯示天氣資訊

以下範例讓使用者輸入城市名稱,程式呼叫天氣 API 取得 JSON,解析後把國家、溫度、濕度與氣壓填進畫面。

步驟說明
1用 Android Studio 建立專案並命名為 JSONParser,Target SDK 選擇較新版本
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,選擇真機或模擬器安裝並驗證結果

主 Activity 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/textView2"
        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"
        android:textAppearance="?android:attr/textAppearanceSmall" />

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

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

    <TextView android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView4"
        android:layout_below="@+id/testsView4"
        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/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/testsView3"
        android:layout_alignBottom="@+id/testsView3"
        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/testsView5"
        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/testsView5"
        android:layout_alignBottom="@+id/testsView5"
        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(別忘了 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>

執行應用程式,初始畫面如下:

JSON 解析範例的初始畫面

在位置欄位輸入城市(範例使用紐約)後按下 weather 鈕:

輸入城市後的畫面

程式會連上 API、下載對應的 JSON 並解析,再把結果逐欄填回介面。

補充:API 回傳的溫度單位是開爾文,要轉成攝氏度需減 273.15。另外,範例用 while(obj.parsingComplete); 來等待結果,這是忙等寫法,會佔用主執行緒資源;正式專案請改用非同步回呼、LiveData 或 coroutine 處理,並記得對網路失敗與 JSON 格式異常都加上錯誤處理。

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