【PI应用】用Java查询雅虎天气并解析Json数据
2016-10-24 11:42
573 查看
这篇文章是“树莓派查询天气,通过串口彩屏/7219点阵实时显示”的一部分,主要介绍使用Java查询雅虎天气并解析Json返回数据,这里只是将获得的实时天气、未来十天的天气等信息,解析并打印出来,为下一步做准备。关于雅虎天气的相关资源和使用介绍,见我的另一篇文章《【Arduino】【ESP】使用Arduino(ESP8266版本)获取雅虎天气信息,并使用点阵显示......进行中》。
简单说说代码:
1、 new Weather("26198084");// zaoZhuang 传入的是雅虎天气枣庄的Woeid,查询看这里“中国地区雅虎WOEID.xlsx”。传入后获得温湿度、日出日落时间、风速、实时天气和未来十天的天气等信息,保存在变量中。
2、 URL urlObject = new URL(url);传入指定格式的雅虎天气查询Url,返回的是固定格式的Json数据。详细见下图。
3、 这里需要导入json.jar包,可以去网上下载
JSONObject jsonObjectAll = new JSONObject(strJson);// get Channel:query->results->channel
jsonObjectChannel = jsonObjectAll.getJSONObject("query").getJSONObject("results").getJSONObject("channel");
创建JSONObject,调用getJSONObject,返回指定key的数据。可以参考这篇文章《Java构造和解析Json数据的两种方法详解一》Json常用函数:
[align=justify]1)所需JAR包[/align]
[align=justify]org.json.jar[/align]
2)创建JSON对象
[align=justify]JSONObject jSONObject=null;[/align]
[align=justify]try {[/align]
[align=justify]//jSONObject初始化时将字符串类型的JSON串放入即可封装[/align]
[align=justify] jSONObject = new JSONObject(json);[/align]
[align=justify]} catch (JSONException e) { //需要此异常抛出[/align]
[align=justify] e.printStackTrace();[/align]
[align=justify]}[/align]
3)写入JSON串
jSONObject.append("nane","wangsiyu"); //放入key=复杂数据类型
(比如对象类型)
jSONObject.accumulate("sex", "男");
// 放入key=简单数据类型
4)输出JSON串
[align=justify]jSONObject.toString()[/align]
5)读取JSON串
[align=justify]jSONObject.getString(key)[/align]
[align=justify]jSONObject.getInt(key)[/align]
[align=justify]jSONObject.getJSONArray(key)[/align]
[align=justify]jSONObject.getJSONObject(key)[/align]
4、其他的代码贴在这里做个备份,没怎么整理写的很简单。
简单说说代码:
1、 new Weather("26198084");// zaoZhuang 传入的是雅虎天气枣庄的Woeid,查询看这里“中国地区雅虎WOEID.xlsx”。传入后获得温湿度、日出日落时间、风速、实时天气和未来十天的天气等信息,保存在变量中。
2、 URL urlObject = new URL(url);传入指定格式的雅虎天气查询Url,返回的是固定格式的Json数据。详细见下图。
3、 这里需要导入json.jar包,可以去网上下载
JSONObject jsonObjectAll = new JSONObject(strJson);// get Channel:query->results->channel
jsonObjectChannel = jsonObjectAll.getJSONObject("query").getJSONObject("results").getJSONObject("channel");
创建JSONObject,调用getJSONObject,返回指定key的数据。可以参考这篇文章《Java构造和解析Json数据的两种方法详解一》Json常用函数:
[align=justify]1)所需JAR包[/align]
[align=justify]org.json.jar[/align]
2)创建JSON对象
[align=justify]JSONObject jSONObject=null;[/align]
[align=justify]try {[/align]
[align=justify]//jSONObject初始化时将字符串类型的JSON串放入即可封装[/align]
[align=justify] jSONObject = new JSONObject(json);[/align]
[align=justify]} catch (JSONException e) { //需要此异常抛出[/align]
[align=justify] e.printStackTrace();[/align]
[align=justify]}[/align]
3)写入JSON串
jSONObject.append("nane","wangsiyu"); //放入key=复杂数据类型
(比如对象类型)
jSONObject.accumulate("sex", "男");
// 放入key=简单数据类型
4)输出JSON串
[align=justify]jSONObject.toString()[/align]
5)读取JSON串
[align=justify]jSONObject.getString(key)[/align]
[align=justify]jSONObject.getInt(key)[/align]
[align=justify]jSONObject.getJSONArray(key)[/align]
[align=justify]jSONObject.getJSONObject(key)[/align]
4、其他的代码贴在这里做个备份,没怎么整理写的很简单。
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class YahooWeather { public static void main(String[] args) { try { Weather weather = new Weather("26198084");// zaoZhuang // System.out.println(weather); weather.showJsonArrayForecasts(); // System.out.println(weather.getChannel()); } catch (JSONException e) { e.printStackTrace(); } // writeFile("D:\\result.json", jsonString); // System.out.println(readFile("D:\\result.json")); } } class Weather { private String lastBuildDate;// lastBuildDate : "Sat, 15 Oct 2016 09:29 PM // CST" private int humidity; // humidity : "95" private double pressure; // pressure : "34100.95" private double visibility; // visibility : "16.25" private String sunrise; // sunrise : "6:17 am" private String sunset; // sunset : "5:33 pm" private String windSpeed; // speed : "22.53" private JSONObject jsonObjectChannel; private String strJsonAllData; private JSONArray jsonArrayForecasts = new JSONArray(); private Forecast[] forecastsArray = new Forecast[10]; /** * incorrding to woeid input, get valid data: jsonObjectChannel and * jsonAllData * * @param strWoeid * @throws JSONException */ public Weather(String strWoeid) throws JSONException// 26198084 { String url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid=" + strWoeid + "%20and%20u=\"c\"&format=json"; StringBuilder json = new StringBuilder(); try { URL urlObject = new URL(url); URLConnection uc = urlObject.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())); String inputLine = null; while ((inputLine = in.readLine()) != null) { json.append(inputLine); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } strJsonAllData = json.toString(); setChannel(strJsonAllData);// get Channel setForecasts();// Get JSONArray:jsonArrayForecasts // acordding to jsonObjectChannel setOtherInfo();// Get other weather information } @Override public String toString() { return "strJsonAllData:" + strJsonAllData; } public JSONObject getChannel() { return jsonObjectChannel; } private void setChannel(String strJson) throws JSONException { JSONObject jsonObjectAll = new JSONObject(strJson); // get Channel:query->results->channel jsonObjectChannel = jsonObjectAll.getJSONObject("query").getJSONObject("results").getJSONObject("channel"); } private void setForecasts() throws JSONException { // get forecast[] jsonArrayForecasts = jsonObjectChannel.getJSONObject("item").getJSONArray("forecast"); for (int i = 0; i < forecastsArray.length; i++) { forecastsArray[i] = new Forecast(jsonArrayForecasts.getJSONObject(i)); } } private void setOtherInfo() throws JSONException { /* get ohterinformation: channel->..... */ JSONObject jsonObjectAtmosphere = jsonObjectChannel.getJSONObject("atmosphere"); humidity = jsonObjectAtmosphere.getInt("humidity"); pressure = jsonObjectAtmosphere.getDouble("pressure"); visibility = jsonObjectAtmosphere.getDouble("visibility"); sunrise = jsonObjectChannel.getJSONObject("astronomy").getString("sunrise"); sunset = jsonObjectChannel.getJSONObject("astronomy").getString("sunset"); windSpeed = jsonObjectChannel.getJSONObject("wind").getString("speed"); } public void showJsonArrayForecasts() throws JSONException { for (int i = 0; i < jsonArrayForecasts.length(); i++) { JSONObject jsonObject = jsonArrayForecasts.getJSONObject(i); System.out.println("Forecast[" + i + "]:" + jsonObject); } } public void writeFile(String filePath, String content) { try { // String content = "This is the content to write into file"; File file = new File(filePath); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); System.out.println("Write to file Done!!!"); } catch (IOException e) { e.printStackTrace(); } } public String readFile(String filePath) { String content = ""; try { String encoding = "utf-8"; File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// note: // codeing BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { content += lineTxt; // System.out.println(lineTxt); } read.close(); } else { System.out.println("No file"); } } catch (Exception e) { System.out.println("Error in reading file"); e.printStackTrace(); } return content; } } class Forecast { private String date;// date : "15 Oct 2016" private int high;// high : "17" private int code;// code : "11" private int low;// low : "15" private String text;// text : "Showers" private String day;// day : "Sat" public Forecast(JSONObject forecastJSonObj) throws JSONException// { date = forecastJSonObj.getString("date"); high = forecastJSonObj.getInt("high"); low = forecastJSonObj.getInt("low"); code = forecastJSonObj.getInt("code"); text = forecastJSonObj.getString("text"); day = forecastJSonObj.getString("day"); } private String getForecast() { return "{" + date + "," + high + "," + low + "," + code + "," + text + "," + day + "}"; } @Override public String toString() { return getForecast(); } }
相关文章推荐
- 【Android应用开发】-(17)获取Google天气预报通过Xml和JSON解析数据
- Java调用天气接口(百度天气)解析返回的JSON数据
- 利用百度车联网提供的天气查询接口用python查询天气信息以及安卓(Java)利用gson解析数据
- Java调用天气接口(百度天气)解析返回的JSON数据
- Java调用天气接口(百度天气)解析返回的JSON数据
- Android解析中国天气接口JSon数据,应用于天气查询!
- Java之调用天气API及解析JSON数据
- Android解析中国天气接口JSon数据,应用于天气查询!
- JSON与JAVA数据的相互转换(基本应用)
- 很好用的Google 开源项目Gson在java中解析和创建json格式的数据
- 用JSON和XML方法解析查询城市的天气情况
- 正则表达式应用笔记----解析网页,获取并显示“未来三天全国天气预报”(java)
- Json数据格式解析示例 (语言:Java 包:org.json.jar)
- Java解析JSON数据 使用org.json
- 数据结构之应用 "栈(Stack)" 实现: 解析算术表达式及计算求值 (C#/Java)
- 根据经纬度查询地址并对获取的json数据进行解析
- java 解析Json格式数据
- jQuery学习笔记--ajax查询,jQuery解析返回的json数据 详解
- Google Gson解析Json数据应用实例
- window phone7.1 天气预报教程(二)WebClient获取天气和json数据解析显示