編輯:Android 開發實例
Android 內建了四個用來處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 與 JSONTokenizer。
第一步,先確認你想從 JSON 中取得哪些欄位。以下面這段資料為例,我們關注的是溫度:
{ "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }
一份 JSON 檔由多種元件組成,下表整理了各元件的定義:
要解析 JSON 物件,先建立一個 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 回傳該鍵對應的 JSON 物件,getString 則回傳指定鍵的字串值。
除此之外,還有更多方法能讓解析更靈活:
以下範例示範如何使用 JSONObject 類別,實作一個能連線天氣 API、解析 JSON 並顯示結果的氣象 App。
你可以把 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) { // 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/HandleXML.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/mL 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/mL android:layout_alignParentRight="true" android:ems="10" /> <TextView android:id="@+id/mL android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/mL android:layout_below="@+id/mL android:layout_marginTop="68dp" android:text="@string/country" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/mL android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/mL android:layout_marginTop="19dp" android:text="@string/temperature" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/mL android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/mL android:layout_below="@+id/mL android:layout_marginTop="32dp" android:text="@string/humidity" android:textAppearance="?android:attr/textAppearanceSmall" /> <TextView android:id="@+id/mL android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/mL android:layout_below="@+id/mL 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/mL android:layout_toRightOf="@+id/mL android:ems="10" > <requestFocus /> </EditText> <EditText android:id="@+id/editText3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/mL android:layout_alignBottom="@+id/mL 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/mL 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/mL android:layout_alignBottom="@+id/mL 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>
準備好後,把 JSONParser 安裝到 AVD 並啟動。若一切正常,模擬器會顯示如下畫面:
接著在位置欄位輸入任一城市,例如我示範輸入紐約,按下「weather」按鈕後,畫面會像下圖這樣:
按下「weather」後,App 便會連線天氣 API,抓取下載對應的 JSON 檔並加以解析。以紐約為例,會回傳類似如下的資料:
提醒你,這個 API 回傳的溫度以克氏溫標(Kelvin)表示,若想轉換成比較直覺的攝氏溫度,記得自行換算。
Android 進度條教學:Spinner 的宣告與顯示控制
在 Android 中,若任務需要一段時間才能完成,可以透過進度條讓使用者知道「程式正在處理」。進度條有兩種常見外形:進度列(Progress Bar)與旋轉式指標(Sp
Android 自適應背景圖片的正解:NinePatch(.9.png)完整實戰
做 Android UI,幾乎每個人遲早都會撞上同一堵牆:一張背景圖怎麼才能在各種尺寸下都不變形。這篇文章把 NinePatch 從原理、製作到源碼層面的處理流程完整梳理
Android 五大布局完整指南:FrameLayout、LinearLayout、AbsoluteLayout、RelativeLayout、TableLayout
Android 常見五大布局包括 FrameLayout、LinearLayout、AbsoluteLayout、RelativeLayout 與 TableLayout
Android JSON 解析教學:從 API 抓資料到顯示
JSON 是 JavaScript Object Notation 的縮寫,是一種與程式語言無關的資料交換格式。憑藉著輕量且易於讀寫的優勢,它成為 XML 以外相當主流的