1. 程式人生 > >利用android自帶的JSONObject解析json資料

利用android自帶的JSONObject解析json資料

話不多說,直接上程式碼:

json資料:http://www.haoservice.com/docs/6

佈局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.lhc.myhttp.MainActivity"
    android:orientation="vertical">
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="點選查詢當前天氣!"/>
</LinearLayout>
主檔案:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import static android.content.ContentValues.TAG;

public class MainActivity extends Activity {
    //控制元件初始化
    private Button button;
    private  final String address = "http://apis.haoservice.com/weather?cityname=成都&key=你的Key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //設定按鈕的單擊事件
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //網路請求只能在子執行緒中進行
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            URL url = new URL(address);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setRequestMethod("GET");
                            conn.setConnectTimeout(5000);
                            conn.setReadTimeout(5000);
                            InputStream in = conn.getInputStream();
                            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                            StringBuilder builder = new StringBuilder();
                            String line;
                            //判斷是否存在資料
                            while ((line = reader.readLine()) != null) {
                                builder.append(line);
                                //將資料轉化為字串型別
                                String data = builder.toString();

                                //建立一個方法,用來解析得到的json資料
                                parseison(data);
                                //關閉相關資源
                                reader.close();
                                in.close();
                                conn.disconnect();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }



            private void parseison(String data) {
                try {
                    //判斷資料獲取是否成功
                    JSONObject jsonobject = new JSONObject(data);
                    int error_code = jsonobject.getInt("error_code");
                    if (error_code == 0) {
                        JSONObject jsonobject_1 = jsonobject.getJSONObject("result");
                        //當前實況天氣
                        JSONObject json_2 = jsonobject_1.getJSONObject("sk");
                        String temp = json_2.getString("temp");
                        String wind_direction = json_2.getString("wind_direction");
                        String wind_strength = json_2.getString("wind_strength");
                        String humidity = json_2.getString("humidity");
                        String time = json_2.getString("time");
                        Log.d(TAG, "當前溫度:"+temp+"\n"+"當前風向:"+wind_direction+"\n"+"當前風力:"+wind_strength+"\n"+"當前溼度:"+humidity+"\n"+"更新時間:"+time);
                        //當天的天氣狀況JSON資料
                        JSONObject today = jsonobject_1.getJSONObject("today");
                        String output = today.getString("city")+"\n"+
                                today.getString("date_y")+"\n"+
                                today.getString("week")+"\n"+
                                today.getString("temperature")+"\n"+
                                today.getString("weather")+"\n"+
                                today.getString("fa")+"\n"+
                                today.getString("fb")+"\n"+
                                today.getString("wind")+"\n"+
                                today.getString("dressing_index")+"\n"+
                                today.getString("dressing_advice")+"\n"+
                                today.getString("uv_index")+"\n"+
                                today.getString("comfort_index")+"\n"+
                                today.getString("wash_index")+"\n"+
                                today.getString("travel_index")+"\n"+
                                today.getString("exercise_index")+"\n"+
                                today.getString("drying_index");
                        Log.d(TAG, "今天的天氣情況是:"+output);
                    } else {
                        Log.d(TAG, "parseison: 解析錯誤");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}