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

Android 讀取網路 JSON:從字串到可用物件的三個步驟

編輯:Android 開發實例

行動裝置上的資料多半來自網路,而網路上的資料多半是 JSON。JSON 的全名是 JavaScript Object Notation,是一種不依附任何平台的純文字資料格式,語法簡單到用記事本都能讀懂,因此成為 XML 之外最普遍的中立交換格式。這一章帶你把「抓回字串 → 交給 JSONObject → 取出欄位」這條路走一遍。

Android 內建的 JSON 相關類別共有四個:JSONArray、JSONObject、JSONStringer、JSONTokenizer。日常開發真正會用到的是前兩個:物件用 JSONObject,清單用 JSONArray。

開始寫程式前,先確認要抓哪些欄位。以這段天氣 API 的示範回應為例,我們想要的是溫度:

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

看懂 JSON 的四種元素

符號看久了眼花,其實只要記住四種元素就夠:

編號元素說明
1陣列 Array []中括號代表一組清單,元素有順序,用索引取值,對應到 Java 就是 JSONArray。
2物件 Object {}花括號代表一個鍵值集合,用名稱取值,對應到 Java 就是 JSONObject。
3鍵 Key一定是用雙引號包住的字串,與其後的值配成一對。
4值 Value可以是字串、數字、布林、null,也可以是另一個物件或陣列。

解析的兩個階段

階段一,建立最外層的 JSONObject,把整段 JSON 文字餵進建構子:

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

階段二,依層級逐個往下取。這份資料裡,國家碼在 sys 底下,溫度在 main 底下,所以要先取出子物件、再取值:

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

也就是說,getJSONObject() 用來往下鑽一層物件,getString() 用來把值取成字串。若某個鍵的值是清單,就換成 getJSONArray() 取得 JSONArray,再用 length() 與 getJSONObject(i) 遍歷。

這個類別還有其他 getter 可以依型別挑用:

編號方法說明
1get(String name)回傳 Object 型別的原始值,需自行轉型。
2getBoolean(String name)取布林值。
3getDouble(String name)取雙精度浮點數。
4getInt(String name)取整數。
5getLong(String name)取長整數。
6length()回傳這個物件裡鍵值對的數量。
7names()回傳包含所有鍵名稱的陣列。

一個實務建議:如果欄位有缺席的可能(例如某城市沒有回傳濕度),改用 optInt、optString 這類方法並帶入預設值,可以省下大量 try-catch。

範例:解析天氣資料並顯示

下面這個 App 讓使用者輸入城市,程式送出請求、解析回傳的 JSON,把國家、溫度、濕度、氣壓填進畫面。實機或模擬器都能跑。

步驟做法
1用 Android Studio 建立專案,命名為 JSONParser,Target SDK 與 Compile With 選最新版 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編譯執行,在裝置上驗證。

主活動 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) { // Inflate the menu; this adds items //to the action bar if it is present. 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.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; 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) { // TODO Auto-generated catch block 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 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query 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/textVew2" 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/textVew2" 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/textView3" 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/textVew4" android:layout_below="@+id/textView4" 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/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/textVew5" 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>

跑起來看看

把 App 裝進 AVD 啟動,設定無誤時會看到這個畫面:

在位置欄位輸入城市名稱(這裡示範紐約),畫面如下:

按下 Weather 之後,程式會向線上 API 請求 JSON 並解析,再把結果填回各欄位。以紐約為例,回傳內容大致如下:

天氣 API 回傳的溫度數值

要注意這個溫度是開爾文,想轉成攝氏就減 273.15。另外,範例中 while(obj.parsingComplete); 這種忙等寫法會把主執行緒卡死,正式專案請改用非同步回呼(AsyncTask、Volley、Retrofit 或協程),並在解析前先檢查 HTTP 狀態碼與 cod 欄位,避免把錯誤訊息當成正常資料來解析。

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