首页 > 代码库 > 获取重要气象台数据 并解析

获取重要气象台数据 并解析

项目要用到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解析逻辑和服务端返回的数据格式关联很大,需要按照服务端定义的格式一一对应。

获取重要气象台数据 并解析