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

Android JSON 解析入門:用 JSONObject 打造天氣查詢應用

編輯:Android 開發實例

JSON(JavaScript Object Notation)早已成為應用程式之間交換資料的首選格式。它結構輕薄、可讀性高,解析成本遠低於 XML,因此大多數公開 API 都優先提供 JSON 回應。本章要說明的,是如何在 Android 上讀取一段 JSON 資料,並把真正需要的欄位取出來使用。

Android SDK 內建四個與 JSON 相關的類別:JSONArray 負責有序集合、JSONObject 代表鍵值對結構、JSONStringer 用於組出 JSON 字串,而 JSONTokenizer 則提供逐段的詞法分析能力。日常開發中最常打交道的,是前兩者。

開始寫程式之前,先釐清目標:這次要抓的是溫度。以下是一段典型的天氣 API 回應:

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

JSON 的四個基本元素

看清楚結構,解析就成功一半。下表列出組成一份 JSON 文件的關鍵元素:

編號元素與說明
1Array([])
方括號代表 JSON 陣列,元素有順序,通常以 index 取值。
2Object({})
大括號代表 JSON 物件,也就是一組鍵值對。
3Key
物件中的鍵一律是字串,鍵與值配對之後才構成一個物件。
4Value
值可以是字串、整數、浮點數、布林值,也可以是另一個物件或陣列。

解析的兩個步驟

第一步是建立 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() 用來取出嵌套的物件,getString() 則回傳指定鍵的字串值。除此之外,還有一批更細緻的方法可用:

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

實作:一個會查天氣的 App

接著用一個完整範例把上面的觀念串起來:使用者輸入城市名稱,程式連線到天氣 API 取得 JSON,解析後把國碼、溫度、濕度與氣壓顯示在畫面上。要跑起來,請先在真機或模擬器上測試。

步驟做法
1用 Android Studio 建立專案,命名為 JSONParser;建置時 Target SDK 與 Compile With 請對齊最新版 Android SDK,以便使用較新的 API。
2在 src/MainActivity.java 補上主要程式碼。
3在 res/layout/activity_main.xml 加入對應的元件。
4在 res/values/string.xml 補上字串資源。
5新增 src/HandleJSON.java,專責抓取與解析 JSON。
6在 AndroidManifest.xml 加上網路權限。
7執行 App,選擇目標裝置,安裝並驗證結果。

主活動程式 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.SupSuppressLint; 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/textView2" 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/textView4" 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/textView5" 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 裝到 AVD 或真機上啟動,若環境設定無誤,會看到這樣的畫面:

接著在位置欄位輸入任意城市,示範中使用紐約,按下 weather 按鈕:

按下按鈕後,程式會連線天氣 API、下載 JSON 並解析,最後把結果填回各個欄位。

提醒一點:這類 API 回傳的溫度單位是 Kelvin(開爾文),若要顯示成台灣使用者熟悉的攝氏度,必須再減去 273.15 做一次轉換。

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