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

用 JSONArray 與 JSONObject 拆解 Android 的 JSON 資料

編輯:Android 開發實例

行動裝置上的資料多半來自遠端 API,而 JSON 正是這些回應最常見的樣貌。相比 XML,它少了標籤的冗餘,寫起來省事、讀起來清楚,解析速度也更快。本章要帶你看懂一份 JSON 的結構,並用 Android 內建的類別把值取出來。

Android 內建的 JSON 工具共有四個:JSONArray(陣列)、JSONObject(物件)、JSONStringer(組字串用)與 JSONTokenizer(逐段解析用)。實務上八九成的需求,前兩個就足夠應付。

先決定你要什麼。以下這段天氣資料中,我們鎖定的是溫度:

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

看懂 JSON 的組成

編號元素與說明
1Array([])
用方括號包起來的是陣列,裡頭的每個項目都有順序。
2Object({})
用大括號包起來的是物件,由一組組鍵值對構成。
3Key
鍵一定是字串;鍵與值配對,才形成一個完整的物件。
4Value
值可以是字串、整數、浮點數、布林,也可以是巢狀的物件或陣列。

從上面的例子可以看到:sys 與 main 是巢狀物件,weather 則是物件陣列——想取出天氣描述,得先進陣列再進物件。

解析流程

先把整段文字包成 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");

還有這些方法可以搭配使用:

編號方法與說明
1get(String name) 以 Object 型別回傳,需自行轉型。
2getBoolean(String name) 回傳布林值。
3getDouble(String name) 回傳 double 數值。
4getInt(String name) 回傳整數。
5getLong(String name) 回傳 long 數值。
6length() 回傳鍵值對的數量。
7names() 回傳所有鍵名稱組成的陣列。

如果欄位可能不存在,改用 optString()、optInt() 這類 opt 系列方法會更保險,它們在找不到鍵時回傳預設值而不丟例外。

動手做:天氣查詢 App

接下來把這些片段組裝成一個真正會連網的程式:輸入城市、按下按鈕、取得 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 負責抓取與解析。
6於 AndroidManifest.xml 加上 INTERNET 權限。
7執行、安裝並驗證。

主活動:

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

網路與解析:

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

版面:

 <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/textViem2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textViem1" 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/textViem2" 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/textViem3" android:layout_below="@+id/textViem3" android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textViem4" android:layout_below="@+id/textViem4" 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/textViem3" android:layout_toRightOf="@+id/textViem3" android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/textViem3" android:layout_alignBottom="@+id/textViem3" 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/textViem5" 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/textViem5" android:layout_alignBottom="@+id/textViem5" 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>

字串與權限:

 <?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>
 <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

執行後的初始畫面:

在位置欄位填入城市(示範用紐約),按下 weather:

程式會連上 API、下載 JSON 並解析,把國碼、溫度、濕度與氣壓填進各欄位。

兩個實務提醒:一是回傳的溫度是開爾文,要轉攝氏需減 273.15;二是範例用 while(obj.parsingComplete); 空迴圈等待,會佔住主執行緒(UI 執行緒)造成 ANR,正式專案請改用非同步回呼或 LiveData 等機制,別把網路與等待放在主執行緒。

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