获取重要气象台数据并解析 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 技术分享 >

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

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:23


项目要用到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解析逻辑和办事端返回的数据格式接洽关系很大年夜,须要按照办事端定义的格式一一对应。

相关案例查看更多