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

Android 端如何解析 JSON?JSONObject 用法與天氣 App 完整實作

編輯:Android 開發實例

JSON 的全名是 JavaScript Object Notation,但今日它早已脫離 JavaScript 的框架,成為跨語言通用的資料交換格式,也是 XML 在 API 世界裡最主要的替代方案。它沒有冗餘的封閉標籤,人眼可讀、機器好解析,行動裝置在行動網路上傳輸時尤其吃香。

本章示範如何在 Android 上把一段 JSON 文字拆解成可用的資料。Android 內建了四個相關類別: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 的組成元素

編號元素與說明
1Array([]) 方括號代表陣列,元素依序排列。
2Object({}) 大括號代表物件,由鍵值對組成。
3Key 鍵必為字串,鍵與值配對後構成一個物件。
4Value 值可以是字串、整數、double、布林,或另一層物件/陣列。

解析步驟

先把整段字串交給 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() 這類方法可避免丟出 JSONException;陣列則用 getJSONArray() 取出後,再以 length() 搭配迴圈逐一處理。

範例:解析天氣 API 並顯示結果

以下範例做出一個天氣查詢 App,輸入城市後連線 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 負責抓取與解析。
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/textViem1" 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/textViem1" 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/textViem1" android:layout_below="@+id/textViem1" android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/textViem3" 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/textViem4" 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>

裝到 AVD 啟動後的初始畫面:

在位置欄位輸入城市,示範使用紐約,按下 weather:

程式會連上 API、取得 JSON 並解析,把結果填入畫面各欄位。

最後兩點提醒:回傳的溫度是開爾文,換成攝氏度需減去 273.15;另外,Android 3.0 以後不允許在主執行緒進行網路連線,範例中的空迴圈等待也會阻塞 UI,正式開發請改用 ExecutorService、Kotlin 協程或 WorkManager 搭配回呼來更新畫面。

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