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

在 Android 中解析 JSON:從語法到天氣查詢實作

編輯:Android 開發實例

行動裝置上的資料,大多以 JSON 的形式從伺服器流過來。它源自 JavaScript 的物件寫法,卻早已成為語言中立的通用格式,憑著結構清爽、可讀性高,逐步取代 XML 成為 API 回應的主流選擇。

Android 內建四個處理 JSON 的類別:JSONArray、JSONObject、JSONStringer 和 JSONTokenizer。日常開發中,最常打交道的是 JSONObject。

解析工作可以拆成兩步:先確認你要抓哪個欄位,再依結構逐層剝開。以下面這段天氣資料為例,目標是溫度:

 { "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 { }大括號表示物件,是構成 JSON 的基礎單位。
3Key物件中的鍵必為字串;鍵與值成對出現,共同組成一個物件。
4Value鍵所對應的值,可能是字串、整數、浮點數或布林值。

解析的兩個動作

先把整段 JSON 文字塞進 JSONObject 建構子:

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

再依巢狀結構逐層取值。內層物件要先用 getJSONObject() 取出,才能讀取其中的欄位:

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

除了 getJSONObject() 與 getString(),JSONObject 還有一整組型別化的取值方法:

編號方法說明
1get(String name)回傳 Object 型別的原始值。
2getBoolean(String name)取得指定鍵的布林值。
3getDouble(String name)取得指定鍵的 double 值。
4getInt(String name)取得指定鍵的整數值。
5getLong(String name)取得指定鍵的 long 值。
6length()回傳此物件所含鍵值對的數量。
7names()回傳一個陣列,列出此物件所有的鍵名稱。

範例:串接天氣 API 並解析顯示

接下來把上面的知識用在真實場景:使用者輸入城市名稱,App 連網取得 JSON,解析後顯示國家、溫度、濕度與氣壓。

步驟做法
1以 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本都採用最新的 Android SDK。
2修改 src/MainActivity.java,加入主要程式碼。
3修改 res/layout/activity_main.xml,加入對應的 XML 元件。
4修改 res/values/string.xml,補齊字串資源。
5新增 src/HandleJSON.java,負責抓取並解析遠端資料。
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.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() : "";
}
} 

版面檔 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/text iew1"
android:layout_alignParentRight="true" android:ems="10" />
<TextView android:id="@+id/text iew2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew1"
android:layout_below="@+id/text iew1" android:layout_marginTop="68dp"
android:text="@string/country"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText android:id="@+id/editText2" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2"
android:layout_below="@+id/text iew2" android:ems="10" >
<requestFocus /> </EditText>
<TextView android:id="@+id/text iew3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew2"
android:layout_below="@+id/editText2" android:layout_marginTop="19dp"
android:text="@string/temperature"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText android:id="@+id/editText3" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText2"
android:layout_below="@+id/text iew3" android:ems="10" />
<TextView android:id="@+id/text iew4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew3"
android:layout_below="@+id/editText3" android:layout_marginTop="32dp"
android:text="@string/humidity"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText android:id="@+id/editText4" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/text iew4" android:ems="10" />
<TextView android:id="@+id/text iew5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/text iew4"
android:layout_below="@+id/editText4" android:layout_marginTop="21dp"
android:text="@string/pressure"
android:textAppearance="?android:attr/textAppearanceSmall" />
<EditText android:id="@+id/editText5" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText4"
android:layout_below="@+id/text iew5" 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="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 一定要宣告 android.permission.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 之後,App 會向天氣服務索取 JSON 並完成解析,把結果填進各個欄位。

要留意的是,回傳的溫度是凱氏。若想轉成比較直覺的攝氏,記得減去 273.15。

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