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

Android 端如何解析 JSON:以天氣查詢 App 為例

編輯:Android 開發實例

行動應用要顯示即時資訊,幾乎都得向伺服器要資料,而回傳格式十之八九是 JSON。它源自 JavaScript 的物件語法,但早已是語言中立的文字格式,任何平台都能讀。相比 XML,JSON 沒有結束標籤、符號少、體積小,解析速度自然更快。

Android 內建四個 JSON 相關類別:JSONObject、JSONArray、JSONStringer、JSONTokenizer。日常開發只需要前兩個:物件用大括號包、陣列用方括號包。

先確認你要抓哪一格

寫解析程式前,先把回傳內容攤開來看。以天氣服務為例,我們關心的是溫度:

 {
  "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 },
  "weather": [ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ],
  "main": { "temp":304.15, "pressure":1009 }
}

溫度藏在 main 這個子物件裡,所以解析時必須先進到那一層,才取得 temp。

JSON 的四個名詞

名詞說明
Array [ ]方括號代表陣列,通常用來裝多筆同類資料。
Object { }大括號代表物件,是鍵值對的集合。
Key物件中的鍵,型別固定為字串;鍵與值配對才構成物件。
Value對應的值,可以是字串、整數、浮點數、布林或 null。

解析的寫法

把整段文字交給 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() 負責往下一層鑽,getString() 則把值取成字串。若需要其他型別,JSONObject 另有完整的一組方法:

方法說明
get(String name)回傳 Object 型別的原始值,需自行轉型。
getBoolean(String name)取得布林值。
getDouble(String name)取得 double。
getInt(String name)取得整數。
getLong(String name)取得 long。
length()回傳鍵值對數量。
names()回傳所有鍵名稱組成的陣列。

範例:JSONParser 天氣查詢

接下來把解析技巧放進真實場景:輸入城市名稱,抓回國家、溫度、濕度與氣壓並顯示。範例使用公開的天氣 API 端點,可在實機或模擬器執行。

步驟做法
1用 Android Studio 建立專案 JSONParser,SDK 版本挑較新的。
2編輯 src/MainActivity.java。
3編輯 res/layout/activity_main.xml 加入表單元件。
4編輯 res/values/string.xml 加入字串。
5新增 src/HandleJSON.java 負責連線與解析。
6在 AndroidManifest.xml 加上網路權限。
7執行並驗證。

主活動 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/textViedw1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_alignParentTop="true"
        android:layout_marginTop="15dp" android:text="@string/location" />
    <EditText android:id="@+id/editText1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <TextView android:id="@+id/textViedw2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/country" />
    <EditText android:id="@+id/editText2" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <TextView android:id="@+id/textViedw3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/temperature" />
    <EditText android:id="@+id/editText3" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <TextView android:id="@+id/textViedw4" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/humidity" />
    <EditText android:id="@+id/editText4" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <TextView android:id="@+id/textViedw5" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="@string/pressure" />
    <EditText android:id="@+id/editText5" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:ems="10" />
    <Button android:id="@+id/button1" android:layout_width="wrap_content"
        android:layout_height="wrap_content" 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 務必加上 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-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,畫面如下:

在位置欄位輸入城市(示範為紐約),畫面會先把你按下按鈕後要請的網址顯示出來,接著才帶出查詢結果:

按下 weather 之後,程式會連上 API、取得 JSON 並解析。還有一點務必留意:這個服務回傳的溫度是克氏(Kelvin),想顯示成攝氏必須換算。

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