Java调用天气接口(百度天气)解析返回的JSON数据

    本文详细讲述了通过Java调用百度天气接口的方法,取得返回的JSON格式的数据,并且通过第三方包解析JSON格式的数据。


  

   通过百度天气API调用网络编程接口接收返回的JSON格式的数据。

   关于百度天气接口的详细说明可以参考文章: http://www.cnblogs.com/txw1958/p/baidu-weather-forecast-api.html

   

  使用百度提供的天气接口,也就是通过一个URL访问百度天气服务器,通过给URL可以取得包含天气信息的JSON格式的数据。

   

<span style="font-size:14px;">package com.cntv.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

public class RequestAbstract {
	// 根据城市获取天气信息的java代码
	// cityName 是你要取得天气信息的城市的中文名字,如“北京”,“深圳”
	public static String getWeatherInform(String cityName) {

		// 百度天气API
		String baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
		StringBuffer strBuf;

		try {
			// 通过浏览器直接访问http://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=5slgyqGDENN7Sy7pw29IUvrZ
			// 5slgyqGDENN7Sy7pw29IUvrZ 是我自己申请的一个AK(许可码),如果访问不了,可以自己去申请一个新的ak
			// 百度ak申请地址:http://lbsyun.baidu.com/apiconsole/key
			// 要访问的地址URL,通过URLEncoder.encode()函数对于中文进行转码
			baiduUrl = "http://api.map.baidu.com/telematics/v3/weather?location=" + URLEncoder.encode(cityName, "utf-8")
					+ "&output=json&ak=eawxnLAbda5AaWTKR8VzdjGMZc4Bpr5Y";
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}

		strBuf = new StringBuffer();

		try {
			URL url = new URL(baiduUrl);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));// 转码。
			String line = null;
			while ((line = reader.readLine()) != null)
				strBuf.append(line + " ");
			reader.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return strBuf.toString();
	}
	public static void main(String[] args) {
		String n=getWeatherInform("上海");
		System.out.println(n);
	}
}
</span>

  上面调用百度天气接口的函数返回的JSON格式的数据如下:


  

 

     

    

    现在需要对该JSON格式的数据进行解析。

    上面返回的JSON格式的数据包含四天的天气信息。现在对JSON格式的数据进行解析。

     

<span style="font-size:18px;">package com.cntv.test.bean;

import java.util.Date;

import com.cntv.test.RequestAbstract;

//需要导入解析JSON格式数据的第三方包   请百度搜索并下载,导入“jsonlib.rar”包  
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class ExpressJson {
	// 解析JSON数据 要解析的JSON数据:strPar
	// WeatherInf 是自己定义的承载所有的天气信息的实体类,包含了四天的天气信息。详细定义见后面。
	static WeatherInf resolveWeatherInf(String strPar){  
	          
	         JSONObject dataOfJson = JSONObject.fromObject(strPar);  
	              
	         if(dataOfJson.getInt("error")!=0){  
	             return null;  
	         }  
	         //保存全部的天气信息。  
	         WeatherInf weatherInf = new WeatherInf();  
	  
	         //从json数据中取得的时间�?  
	            String date = dataOfJson.getString("date");  
	            int year = Integer.parseInt(date.substring(0, 4));  
	            int month = Integer.parseInt(date.substring(5, 7));  
	            int day = Integer.parseInt(date.substring(8, 10));  
	            Date today = new Date(year-1900,month-1,day);  
	  
	            JSONArray results=dataOfJson.getJSONArray("results");  
	            JSONObject results0=results.getJSONObject(0);  
	              
	            String location = results0.getString("currentCity");  
	            int pmTwoPointFive;  
	  
	            if(results0.getString("pm25").isEmpty()){  
	                pmTwoPointFive = 0;  
	            }else{  
	                pmTwoPointFive = results0.getInt("pm25");  
	            }  
	            //System.out.println(results0.get("pm25").toString()+"11");  
	              
	            try{  
	                  
	                JSONArray index = results0.getJSONArray("index");  
	                  
	                JSONObject index0 = index.getJSONObject(0);//穿衣  
	                JSONObject index1 = index.getJSONObject(1);//洗车  
	                JSONObject index2 = index.getJSONObject(2);//感冒  
	                JSONObject index3 = index.getJSONObject(3);//运动  
	                JSONObject index4 = index.getJSONObject(4);//紫外线强度  
	                  
	  
	                String dressAdvise = index0.getString("des");//穿衣建议  
	                String washCarAdvise = index1.getString("des");//洗车建议  
	                String coldAdvise = index2.getString("des");//感冒建议  
	                String sportsAdvise = index3.getString("des");//运动建议  
	                String ultravioletRaysAdvise = index4.getString("des");//紫外线建议  
	                  
	                weatherInf.setDressAdvise(dressAdvise);  
	                weatherInf.setWashCarAdvise(washCarAdvise);  
	                weatherInf.setColdAdvise(coldAdvise);  
	                weatherInf.setSportsAdvise(sportsAdvise);  
	                weatherInf.setUltravioletRaysAdvise(ultravioletRaysAdvise);  
	                  
	            }catch(JSONException jsonExp){  
	                  
	                weatherInf.setDressAdvise("要温度,也要风度。天热缓减衣,天凉及添衣!");  
	                weatherInf.setWashCarAdvise("你洗还是不洗,灰尘都在哪里,不增不减。");  
	                weatherInf.setColdAdvise("一天一个苹果,感冒不来找我!多吃水果和蔬菜。");  
	                weatherInf.setSportsAdvise("生命在于运动!不要总宅在家里哦!");  
	                weatherInf.setUltravioletRaysAdvise("心灵可以永远年轻,皮肤也一样可以!");  
	            }  
	                  
	            JSONArray weather_data = results0.getJSONArray("weather_data");//weather_data中有四项�?  
	              
	                        //OneDayWeatherInf是自己定义的承载某一天的天气信息的实体类,详细定义见后面。  
	            OneDayWeatherInf[] oneDayWeatherInfS = new OneDayWeatherInf[4];  
	            for(int i=0;i<4;i++){  
	                oneDayWeatherInfS[i] = new OneDayWeatherInf();  
	            }  
	              
	            for(int i=0;i<weather_data.size();i++){  
	                  
	                JSONObject OneDayWeatherinfo=weather_data.getJSONObject(i);  
	                String dayData = OneDayWeatherinfo.getString("date");  
	                OneDayWeatherInf oneDayWeatherInf = new OneDayWeatherInf();  
	  
	                oneDayWeatherInf.setDate((today.getYear()+1900)+"."+(today.getMonth()+1)+"."+today.getDate());  
	                today.setDate(today.getDate()+1);//增加一天  
	                  
	                oneDayWeatherInf.setLocation(location);  
	                oneDayWeatherInf.setPmTwoPointFive(pmTwoPointFive);  
	                  
	                if(i==0){//第一个,也就是当天的天气,在date字段中最后包含了实时天气  
	                    int beginIndex = dayData.indexOf(":");  
	                    int endIndex = dayData.indexOf(")");  
	                    if(beginIndex>-1){  
	                        oneDayWeatherInf.setTempertureNow(dayData.substring(beginIndex+1, endIndex));  
	                        oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date").substring(0,2));  
	                    }else{  
	                        oneDayWeatherInf.setTempertureNow(" ");  
	                        oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date").substring(0,2));  
	                    }  
	  
	                }else{  
	                    oneDayWeatherInf.setWeek(OneDayWeatherinfo.getString("date"));  
	                }  
	                  
	                oneDayWeatherInf.setTempertureOfDay(OneDayWeatherinfo.getString("temperature"));  
//	                oneDayWeatherInf.setWeather(<span style="font-family: Arial, Helvetica, sans-serif;">OneDayWeatherinfo.getString("weather")</span><span style="font-family: Arial, Helvetica, sans-serif;">);</span>  
//	                oneDayWeatherInf.setWeather(weather);  
	                oneDayWeatherInf.setWind(OneDayWeatherinfo.getString("wind"));  
	                              
	                oneDayWeatherInfS[i] = oneDayWeatherInf;  
	            }  
	              
	            weatherInf.setWeatherInfs(oneDayWeatherInfS);  
	  
	        return weatherInf;  
	    }
	public static void main(String[] args) {
		
		String wea=RequestAbstract.getWeatherInform("成都");
		WeatherInf in=ExpressJson.resolveWeatherInf(wea);
		System.out.println(in.getColdAdvise());
		System.out.println(in.getSportsAdvise());
		
	}
}
</span>

   现在就将JSON格式的数据提取出来放到Java中的实体类中了。

   

<span style="font-size:18px;">package com.cntv.test.bean;

public class WeatherInf {
	 private OneDayWeatherInf[] weatherInfs;  
	    private String dressAdvise;//穿衣建议  
	    private String washCarAdvise;//洗车建议  
	    private String coldAdvise;//感冒建议  
	    private String sportsAdvise;//运动建议  
	    private String ultravioletRaysAdvise;//紫外线建议  
	      
	      
	    public WeatherInf(){  
	        dressAdvise = "";  
	        washCarAdvise = "";  
	        coldAdvise = "";  
	        sportsAdvise = "";  
	        ultravioletRaysAdvise = "";  
	    }  
	      
	    public void printInf(){  
	          
	        System.out.println(dressAdvise);  
	        System.out.println(washCarAdvise);  
	        System.out.println(coldAdvise);  
	        System.out.println(sportsAdvise);  
	        System.out.println(ultravioletRaysAdvise);  
	        for(int i=0;i<weatherInfs.length;i++){  
	            System.out.println(weatherInfs[i]);  
	        }  
	          
	    }  
	      
	  
	    public OneDayWeatherInf[] getWeatherInfs() {  
	        return weatherInfs;  
	    }  
	  
	  
	    public void setWeatherInfs(OneDayWeatherInf[] weatherInfs) {  
	        this.weatherInfs = weatherInfs;  
	    }  
	  
	  
	    public String getDressAdvise() {  
	        return dressAdvise;  
	    }  
	  
	  
	    public void setDressAdvise(String dressAdvise) {  
	        this.dressAdvise = dressAdvise;  
	    }  
	  
	  
	    public String getWashCarAdvise() {  
	        return washCarAdvise;  
	    }  
	  
	  
	    public void setWashCarAdvise(String washCarAdvise) {  
	        this.washCarAdvise = washCarAdvise;  
	    }  
	  
	  
	    public String getColdAdvise() {  
	        return coldAdvise;  
	    }  
	  
	  
	    public void setColdAdvise(String coldAdvise) {  
	        this.coldAdvise = coldAdvise;  
	    }  
	  
	  
	    public String getSportsAdvise() {  
	        return sportsAdvise;  
	    }  
	  
	  
	    public void setSportsAdvise(String sportsAdvise) {  
	        this.sportsAdvise = sportsAdvise;  
	    }  
	  
	  
	    public String getUltravioletRaysAdvise() {  
	        return ultravioletRaysAdvise;  
	    }  
	  
	  
	    public void setUltravioletRaysAdvise(String ultravioletRaysAdvise) {  
	        this.ultravioletRaysAdvise = ultravioletRaysAdvise;  
	    }  
}</span>

  OneDayWeatherInf实体类

  

package com.cntv.test.bean;

public class OneDayWeatherInf {
	 private    
     String location;    
     String date;    
     String week;    
     String tempertureOfDay;    
     String tempertureNow;    
     String wind;    
     String weather;     
     String picture;    
     int pmTwoPointFive;    
 
 public OneDayWeatherInf(){    
         
     location = "";    
     date = "";    
     week = "";    
     tempertureOfDay = "";    
     tempertureNow = "";    
     wind = "";    
     weather = "";    
     picture = "undefined";    
     pmTwoPointFive = 0;    
 }    
         
         
         
 public String getLocation() {    
     return location;    
 }    
 public void setLocation(String location) {    
     this.location = location;    
 }    
 public String getDate() {    
     return date;    
 }    
 public void setDate(String date) {    
     this.date = date;    
 }    
 public String getWeek() {    
     return week;    
 }    
 public void setWeek(String week) {    
     this.week = week;    
 }    
 public String getTempertureOfDay() {    
     return tempertureOfDay;    
 }    
 public void setTempertureOfDay(String tempertureOfDay) {    
     this.tempertureOfDay = tempertureOfDay;    
 }    
 public String getTempertureNow() {    
     return tempertureNow;    
 }    
 public void setTempertureNow(String tempertureNow) {    
     this.tempertureNow = tempertureNow;    
 }    
 public String getWind() {    
     return wind;    
 }    
 public void setWind(String wind) {    
     this.wind = wind;    
 }    
 public String getWeather() {    
     return weather;    
 }    
 public void setWeather(String weather) {    
     this.weather = weather;    
 }    
 public String getPicture() {    
     return picture;    
 }    
 public void setPicture(String picture) {    
     this.picture = picture;    
 }    
 public int getPmTwoPointFive() {    
     return pmTwoPointFive;    
 }    
 public void setPmTwoPointFive(int pmTwoPointFive) {    
     this.pmTwoPointFive = pmTwoPointFive;    
 }    
 
 public String toString(){    
         
     return location+"   "+date+"   "+week+" tempertureOfDay:  "+tempertureOfDay+" tempertureNow:  "+tempertureNow+"   "+wind+"   "+weather+"   "+picture+"   "+pmTwoPointFive;    
 }    
     
}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值