Android json解析网络数据实现天气实时查询

首先看北京天气网络数据,打开这个网页: http://www.weather.com.cn/data/sk/101010100.html

{"weatherinfo":{"city":"北京","cityid":"101010100","temp":"22","WD":"东风","WS":"1级","SD":"33%","WSE":"1","time":"21:25","isRadar":"1","Radar":"JC_RADAR_AZ9010_JB"}}
这是Json格式数据,下面来解析这些数据,实现天气查询

新建一个Android工程,添加一个class:JsonUtils.java


package cn.itcast.net.jsonparse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;


import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.stream.JsonReader;

public class JsonUtils {

	public static String getConnection(String path)  
            throws MalformedURLException, IOException, ProtocolException {  
        URL url = new URL(path);  
        try {  
//        	建立一个http连接
            HttpURLConnection cn = (HttpURLConnection) url.openConnection();  
//            5秒超时
            cn.setConnectTimeout(5 * 1000);  
//            使用Get方法传递数据
            cn.setRequestMethod("GET");   
            InputStreamReader in = new InputStreamReader(cn.getInputStream());  
//             流数据读取
            BufferedReader buff = new BufferedReader(in);  
            String data = buff.readLine().toString();  
            System.out.println("流数据data:    " + data);  
            buff.close();  
            in.close(); 
//            返回数据流
            return data;  
        } 
        catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
            System.out.println("查询失败,请检查网络...");  
            return null;  
        }  
    }  
	public  List<Map<String, String>> getWeather(String path) {  
		  
	    List<Map<String, String>> list = new ArrayList<Map<String, String>>();  
	    String json = null;  
	    Map<String, String> map;  	  
	    try { 
//	    	调用getConnection()获得数据流
	        String line = getConnection(path);  	  
	        if (line != null) {  
	            json = new String(line);  
	            // 对象的形式  
	            JSONObject Item = new JSONObject(json);  
	            // 得到对象中的对象  
	            JSONObject item = Item.getJSONObject("weatherinfo");  
	            String city = item.getString("city");  
	            String temp = item.getString("temp");  
	            String time = item.getString("time");    
	            // 添加到map中  	  
	            map = new HashMap<String, String>();  
	            map.put("city", city);  
	            map.put("temp", temp);    
	            map.put("time", time); 
	            list.add(map); 
	        } 
	        else { 
	            System.out.println("获取流数据失败!");  
	        }  
	  
	    } catch (MalformedURLException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    } catch (ProtocolException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    } catch (IOException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    } catch (JSONException e) {  
	        // TODO Auto-generated catch block  
	        e.printStackTrace();  
	    }  
	    return list;  
	}  

在需要使用的activity调用:

package com.example.weather;

import java.util.List;
import java.util.Map;

import cn.itcast.net.jsonparse.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.TextView;
public class weatherActivity extends Activity {
    private TextView textView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);  
		setContentView(R.layout.weather);
//		找到控件
		findViews();	
	}

	@SuppressWarnings("rawtypes")
	private void findViews() {
		
		textView = (TextView)findViewById(R.id.WeathertextView1);
//		json数据解析
		JsonUtils jsonUtils = new JsonUtils();
//		北京天气网络数据
		 String path ="http://www.weather.com.cn/data/sk/101010100.html";
		 List list= jsonUtils.getWeather(path);
		 if(!list.isEmpty())
		 {
			 Map map =(Map) list.get(0);
             if(!map.isEmpty())
             {
    			 String time="发布时间:" +(String) map.get("time")+"\n";
    			 String city="当前城市:"+(String) map.get("city")+"\n";
    			 String temp="实时温度:"+(String) map.get("temp")+"℃";
    			 String message =time+city+temp;
//    			 将解析数据放置到textView里显示
    			 textView.setText((CharSequence) message); 
             }

		 }
		 else
		 {
			 AlertDialog.Builder build=new AlertDialog.Builder(this);
			 build.setTitle("提示")  
             .setMessage("网络出现故障,请稍后重试!")  
             .setPositiveButton("确定", new DialogInterface.OnClickListener() {  
                   
                 @Override  
                 public void onClick(DialogInterface dialog, int which) {  
                     // TODO Auto-generated method stub  
                 }  
             }).show(); 
	
		 }
		
		
	}
}

注意:这里涉及访问网络,那么要在AndroidManifest.xml开启权限,否则会报相关错误!

<!-- 访问internet权限 -->
<uses-permission android:name="android.permission.INTERNET"/>

顺便指出:我们在向SD卡里写入或读取数据时也要在AndroidManifest.xml开启相应权限:

<!-- 在SDCard中创建与删除文件权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

运行截图:


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,我可以为你提供一些解析 JSON 数据并在 Android Studio 中显示天气预报和生活指数的基本步骤: 1. 首先,你需要获取天气数据的 API 接口,例如和风天气提供的天气预报 API:https://dev.heweather.com/docs/api/weather 2. 然后,你需要使用 Android 中提供的网络请求库,比如 Volley 或 OkHttp,来获取天气数据。你可以使用以下代码来发送 GET 请求并获取 JSON 数据: ``` String url = "your_weather_api_url_here"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { // 处理 JSON 数据 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // 处理错误 } }); // 将请求添加到请求队列中 RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonObjectRequest); ``` 3. 接下来,你需要解析 JSON 数据并将它转换为 Java 对象。你可以使用 Gson 这个库来实现 JSON 数据和 Java 对象之间的转换。以下是一个使用 Gson 解析 JSON 数据的示例代码: ```java Gson gson = new Gson(); WeatherData weatherData = gson.fromJson(response.toString(), WeatherData.class); ``` 其中,WeatherData 是一个 POJO 类,它包含了从 JSON 数据解析出来的天气信息。 4. 最后,你需要将天气信息显示在你的应用程序界面上。你可以使用 RecyclerView 或 ListView 来显示每天的天气预报信息,使用 TextView 显示当前天气信息和生活指数信息。以下是一个示例布局文件: ```xml <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/current_weather" android:layout_width="match_parent" android:layout_height="wrap_content" /> <RecyclerView android:id="@+id/daily_forecast" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/life_index" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> ``` 以上就是在 Android Studio 中解析 JSON 数据并显示天气预报和生活指数的基本步骤。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值