获取重要气象台数据并解析
发表时间:2020-10-19
发布人:葵宇科技
浏览次数:48
项目要用到json解析,写了一个demo,大年夜中心气候台获取json数据并解析到本地。记录一下。
联网获取数据逻辑:
private void loadData(){
Log.d("wlj", "loadData >>>>> ");
HttpParams params=new BasicHttpParams();
//设置连接超时或响应超时
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
HttpClient client = new DefaultHttpClient(params);
HttpGet request = new HttpGet("http://m.weather.com.cn/data/101280601.html");
HttpResponse response;
InputStream is;
try {
response = client.execute(request);
if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
is = response.getEntity().getContent();
json(is);
}else{
Log.d("wlj", "获取收集数据掉败 ... ");
}
} catch (ClientProtocolException e) {
Log.d("wlj", "ClientProtocolException ... ");
e.printStackTrace();
} catch (IOException e) {
Log.d("wlj", "IOException ... ");
e.printStackTrace();
}finally{
client.getConnectionManager().shutdown();
}
}
json数据解析逻辑:
private void json(InputStream is){
JsonReader reader = null;
try {
reader = new JsonReader(new InputStreamReader(is, "UTF-8"));
reader.beginObject();
if(reader.nextName().equalsIgnoreCase("weatherinfo")){
reader.beginObject();
while(reader.hasNext()){
String name = reader.nextName();
if(name.equalsIgnoreCase("city_en")){
Log.d("wlj", "city is " + reader.nextString());
}else if(name.equalsIgnoreCase("temp5")){
Log.d("wlj", "temp5 is " + reader.nextString());
}else if(name.equalsIgnoreCase("index_d")){
Log.d("wlj", "index_d is " + reader.nextString());
}else{
reader.skipValue();
}
}
reader.endObject();
}
reader.endObject();
} catch (IOException e) {
Log.d("wlj", "parse reader IOException ... ");
e.printStackTrace();
}finally{
try {
if(is != null) is.close();
if(reader != null) reader.close();
} catch (IOException e) {
Log.d("wlj", "close reader IOException ... ");
e.printStackTrace();
}
}
}大年夜json的解析逻辑可以看出,json解析逻辑和办事端返回的数据格式接洽关系很大年夜,须要按照办事端定义的格式一一对应。








