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 相關類別: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 { }大括號代表物件。
3Key物件中的鍵為字串,鍵值成對構成物件。
4Value對應的值,可能是字串、整數或 double。

解析流程

先建立 JSONObject,把含 JSON 資料的字串交給它:

 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() 回傳指定鍵的字串值。此外還有一整組方法可用:

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

範例:解析天氣資料並顯示

這個範例做出一個天氣查詢 App:使用者輸入城市,程式抓取 JSON 並解析出國家、溫度、濕度與氣壓。

步驟做法
1用 Android Studio 建立專案 JSONParser,Target SDK 與編譯版本採最新 SDK。
2修改 src/MainActivity.java,加入程式碼。
3修改 res/layout/activity_main.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/text iew1" 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