編輯:Android 開發實例
JSON 的全名是 JavaScript Object Notation。雖然源自 JavaScript 的物件字面語法,它早已成為獨立、跨語言的資料交換格式,憑藉著簡潔的結構與極低的解析成本,在 API 的世界里幾乎取代了 XML。
本章示範如何在 Android 應用中解析 JSON 並取出需要的欄位,題材同樣選用天氣查詢。
Android 內建四個 JSON 類別:JSONArray、JSONObject、JSONStringer、JSONTokenizer。
以下是一段天氣 API 的回應,本章的目标是取出溫度:
{
"sys": {
"country": "GB",
"sunrise": 1381107633,
"sunset": 1381149604
},
"weather": [
{
"id": 711,
"main": "Smoke",
"description": "smoke",
"icon": "50n"
}
],
"main": {
"temp": 304.15,
"pressure": 1009
}
}
| 編號 | 元素 | 說明 |
|---|---|---|
| 1 | Array([]) | 方括號代表陣列。 |
| 2 | Object({}) | 大括號代表物件。 |
| 3 | Key | 物件中的鍵,為字串;鍵與值成對構成物件。 |
| 4 | Value | 鍵對應的值,可能是字串、整數或 double 等。 |
第一步,把整段 JSON 字串交給 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");
getJSONObject() 回傳巢狀的 JSON 物件,getString() 回傳指定鍵的字串值。除此之外還有這些方法可用:
| 編號 | 方法 | 說明 |
|---|---|---|
| 1 | get(String name) | 只回傳值,型別為 Object。 |
| 2 | getBoolean(String name) | 回傳指定鍵的布林值。 |
| 3 | getDouble(String name) | 回傳指定鍵的 double 值。 |
| 4 | getInt(String name) | 回傳指定鍵的整數值。 |
| 5 | getLong(String name) | 回傳指定鍵的 long 值。 |
| 6 | length() | 回傳這個物件的鍵值對數量。 |
| 7 | names() | 回傳包含所有鍵名的陣列。 |
這個範例會做出一个簡易的天氣查詢程式,讓使用者從天氣 API 取得 JSON 並解析顯示。
| 步驟 | 做法 |
|---|---|
| 1 | 用 Android Studio 建立專案並命名為 JSONParser,Target SDK 與 Compile With 選最新版本。 |
| 2 | 修改 src/MainActivity.java 加入必要程式碼。 |
| 3 | 修改 res/layout/activity_main.xml 加入版面元件。 |
| 4 | 修改 res/values/string.xml 加入字串資源。 |
| 5 | 新增 src/HandleJSON.java,用來取得並解析 JSON。 |
| 6 | 修改 AndroidManifest.xml 加上上網權限。 |
| 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/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/textV TextView2"
android:layout_marginTop="19dp"
android:text="@string/temperature"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView android:id="@+id/textV 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/textV 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/textV 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/textV 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/textV 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/textV 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>
<?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>
<?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 按鈕:
按下按鈕後,程式會連上 Google 天氣 API、索取 JSON 檔並解析它,最後把結果呈現在畫面上。
特別注意:回傳的溫度是開爾文。若想轉成更容易理解的攝氏度,記得補上換算。
Android 本地化指南:讓應用適應不同語言環境
Android 應用可能在不同語言環境的裝置上執行。若要讓應用更貼近使用者,應將文字、數字與其他資源本地化。最常見的做法是把字串放入不同 values 資料夾。 建立本地
Android 應用本地化:多語系字串資源設定
Android App 可能在不同語言與地區運行。本地化可讓文字、數字、日期等更符合當地使用者的習慣。 建立語言資源資料夾 在 res 下建立 values-it、val
動手做「開發者頭條」App(三):首頁整體實現
一、前言 本文是系列第三篇,來把開發者頭條的首頁搭起來。先看效果: 從動圖可以拆出兩層結構:外層是「精選、訂閱、發現」三個可左右滑動的 Tab;進入精選頁後,頂部是一塊
Android 登入應用教學:三次嘗試後停用登入按鈕
這個登入範例會限制使用者最多只能嘗試三次。每次輸入錯誤,剩餘次數會減少;當次數用完,登入按鈕將被停用。 登入畫面元件 畫面中需要使用者名稱、密碼、登入按鈕與剩餘次數文字。