//创建json解析器
JsonParser parser = new JsonParser();
JsonObject object = null;
try {
object = (JsonObject) parser.parse(reader);
} catch (Exception e) {
try {
throw new Exception();
} catch (Exception ex) {
logger.error(storeLocationVO.getStoreCode() + ",Json解析异常", ex);
return;
}
}
//如果获取不到msg直接退出
if (object.get("msg") == null) {
return;
}
String val = object.get("msg").getAsString();
if (val.equals("success")) {
JsonObject data = object.get("data").getAsJsonObject();
JsonObject condition = data.get("condition").getAsJsonObject();
//解析出实况天气的数据并存放进对象
//降水量
actualWeather.setPrecipitation(condition.get("precipitation").getAsString());
//天气情况
actualWeather.setWeather(condition.get("condition").getAsString());
//温度
actualWeather.setTemp(condition.get("temp").getAsString());
//风速
actualWeather.setWindSpeed(condition.get("windSpeed").getAsString());
//更新时间
actualWeather.setUpdateTime(condition.get("updatetime").getAsString());
//将更新时间设置为整点
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(simpleDateFormat.parse(condition.get("updatetime").getAsString()));
} catch (ParseException e) {
e.printStackTrace();
}
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date formatTime = calendar.getTime();
actualWeather.setFormatTime(simpleDateFormat.format(formatTime));
actualWeather.setStoreCode(storeLocationVO.getStoreCode());
//解析出未来24小时的天气并存入对象
JsonArray hourly = data.get("hourly").getAsJsonArray();
int countHourly = 0;
//循环取出每小时的数据,到24小时结束循环
for (JsonElement json : hourly) {
JsonObject object1 = json.getAsJsonObject();
HourlyWeatherModel hourlyWeather = new HourlyWeatherModel();
hourlyWeather.setStoreCode(storeLocationVO.getStoreCode());
//小时
hourlyWeather.setHour(object1.get("hour").getAsString());
//日期
hourlyWeather.setDate(object1.get("date").getAsString());
//当前天气
hourlyWeather.setWeather(object1.get("condition").getAsString());
//温度
hourlyWeather.setTemp(object1.get("temp").getAsString());
//降水量
hourlyWeather.setPrecipitation(object1.get("qpf").getAsString());
//风速
BigDecimal wind = new BigDecimal(object1.get("windSpeed").getAsString());
BigDecimal divisor = wind.multiply(new BigDecimal(1000));
BigDecimal windSpeed = divisor.divide(new BigDecimal(3600), 1, RoundingMode.HALF_UP);
hourlyWeather.setWindSpeed(windSpeed.toString());
hourlyWeatherList.add(hourlyWeather);
countHourly++;
if (countHourly >= 24) {
break;
}
}
}
网友评论