栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


案例效果:

初运行:

点击 “简单天气” 按钮:

点击 “复杂天气” 按钮


案列代码

布局文件: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



这样就完成啦~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/877126.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号