您的位置:首页 > 编程语言 > Java开发

【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、其他的代码贴在这里做个备份,没怎么整理写的很简单。

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();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: