Android学习——解析JSON数据(天气案例)

学习记录:

简单学习一下Android Studio课程中的解析JSON数据。
参考资料: Android JSON数据解析

案列中用到的API地址:
地址1:http://api.qingyunke.com/api.php?key=free&appid=0&msg=上海天气
地址2:http://t.weather.itboy.net/api/weather/city/101020100


案例效果:

初运行:
Android学习——解析JSON数据(天气案例)_第1张图片
点击 “简单天气” 按钮:
Android学习——解析JSON数据(天气案例)_第2张图片
点击 “复杂天气” 按钮
Android学习——解析JSON数据(天气案例)_第3张图片


案列代码

布局文件:activity_main.xml

布局比较简单:2个button 和 1个textView

主活动类:MainActivity.java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.json.JSONArray;
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;

public class MainActivity extends AppCompatActivity {
    private Button btn1,btn2;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView=findViewById(R.id.textView);
        btn1=findViewById(R.id.button);
        btn2=findViewById(R.id.button2);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendRequestWithHttpURLConnection();
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendRequestWithHttpURLConnection2();
            }
        });
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://api.qingyunke.com/api.php?key=free&appid=0&msg=上海天气");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    if(connection.getResponseCode()==200){
                        InputStream in = connection.getInputStream();
                        reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        pareJSON1(response.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void sendRequestWithHttpURLConnection2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL("http://t.weather.itboy.net/api/weather/city/101020100");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    if(connection.getResponseCode()==200) {
                        InputStream in = connection.getInputStream();
                        reader = new BufferedReader(new InputStreamReader(in));
                        StringBuilder response = new StringBuilder();
                        String line;
                        while ((line = reader.readLine()) != null) {
                            response.append(line);
                        }
                        pareJSON2(response.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    //解析 1
    private void pareJSON1(String jsonData){
        try {
            JSONObject jsonObject=new JSONObject(jsonData);
            String result=jsonObject.getString("result");
            String content=jsonObject.getString("content");
            Log.d("MainActivity","今天的天气是:\n"+content);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText("");
                    textView.append(content);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //解析 2
    private void pareJSON2(String jsonData){
        try {
            JSONObject jsonObject=new JSONObject(jsonData);
            String date=jsonObject.getString("date");
            StringBuilder weather=new StringBuilder();
            weather.append("日期:     "+date+"\n");

            String cityInfo=jsonObject.getString("cityInfo");
            JSONObject cityinfoObject=new JSONObject(cityInfo);
            String city=cityinfoObject.getString("city");
            weather.append("城市:     "+city+"\n");

            String data=jsonObject.getString("data");
            JSONObject dataObj=new JSONObject(data);
            weather.append("温度:     "+dataObj.getString("wendu")+"\n");
            weather.append("湿度:     "+dataObj.getString("shidu")+"\n");

            String forecast=dataObj.getString("forecast");
            JSONArray forecast_arr=new JSONArray(forecast);

            for (int i = 0; i < forecast_arr.length(); i++) {
                JSONObject jo=forecast_arr.getJSONObject(i);
                String next_date=jo.getString("ymd");
                String high=jo.getString("high");
                String week=jo.getString("week");
                Log.d("MainActivity", "预报日期: "+next_date);
                Log.d("MainActivity", "高温: "+high);
                Log.d("MainActivity", "星期: "+week);
                weather.append(next_date+" | "+high+" | "+week+"\n");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    textView.setText("");
                    textView.append(weather);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

添加网络访问权限:AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

这样就完成啦~


2022.5.31 更新了布局文件的代码给需要的小伙伴!

activity_main.xml:


<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:layout_margin="30dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text=" "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button2"
        app:layout_constraintVertical_bias="0.068" />

    <Button
        android:id="@+id/button"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="简单天气"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="复杂天气"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button" />

androidx.constraintlayout.widget.ConstraintLayout>

你可能感兴趣的:(android,json,学习)