`

Android json通信(解析)方法

 
阅读更多
下面是在做天气预报程序时用到的Json通信,解析方法,备份一下,下次找就方便了;

1、链接服务器获取json字符串:

	public static String getJsonContent(String city) {
		String urlString="";
		try {
			urlString = URL + "&location=" + URLEncoder.encode(city, "UTF-8")
					+ "&ak=" + APP_KEY;
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(urlString);
			HttpURLConnection httpConn = (HttpURLConnection) url
					.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(8000);
			httpConn.setDoInput(true);
			httpConn.setRequestMethod("GET");
			// 获取相应码
			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				return ConvertStream2Json(httpConn.getInputStream());
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}


	private static String ConvertStream2Json(InputStream inputStream) {
		String jsonStr = "";
		// ByteArrayOutputStream相当于内存输出流
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		// 将输入流转移到内存输出流中
		try {
			while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, len);
			}
			// 将内存流转换为字符串
			jsonStr = new String(out.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonStr;
	}


2、解析Json字符串:
Json的解析无外乎Jsonobject、JsonArray,针对服务器返回的具体字符串进行解析,下面只是给了一个例子,例子对应的Json字符串如下:

result:{
"error":0,"status":"success","date":"2014-07-30",
"results":[
{"currentCity":"北京","pm25":"209",
"index":[
{"title":"穿衣","zs":"热","tipt":"穿衣指数","des":"天气热,建议着短裙、短裤、短薄外套、T恤等夏季服装。"},
{"title":"洗车","zs":"不宜","tipt":"洗车指数","des":"不宜洗车,路面积水较多,不宜擦洗汽车。如果执意擦洗,要做好溅上泥水的心理准备。"},
{"title":"感冒","zs":"较易发","tipt":"感冒指数","des":"相对今天出现了较大幅度降温,较易发生感冒,体质较弱的朋友请注意适当防护。"},
{"title":"运动","zs":"较适宜","tipt":"运动指数","des":"阴天,较适宜进行各种户内外运动。"},
{"title":"紫外线强度","zs":"弱","tipt":"紫外线强度指数","des":"紫外线强度较弱,建议出门前涂擦SPF在12-15之间、PA+的防晒护肤品。"}],
"weather_data":[
{"date":"周三 07月30日 (实时:23℃)","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"多云","wind":"微风","temperature":"29 ~ 24℃"},
{"date":"周四","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/qing.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/qing.png","weather":"晴","wind":"微风","temperature":"31 ~ 24℃"},
{"date":"周五","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/duoyun.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/duoyun.png","weather":"多云","wind":"微风","temperature":"34 ~ 25℃"},
{"date":"周六","dayPictureUrl":"http://api.map.baidu.com/images/weather/day/qing.png","nightPictureUrl":"http://api.map.baidu.com/images/weather/night/qing.png","weather":"晴","wind":"微风","temperature":"34 ~ 24℃"}
]
}
]
}


	public static int getJsonResult(String result) {
		int resultError = 0;
		Map<String, String> reslutMap = new HashMap<String, String>();
		try {
			JSONObject jObject = new JSONObject(result);
			//返回错误码,0为正常,其他请查询状态表;
			resultError = Integer.valueOf(jObject.get("error").toString());
			
			//网络时间
			NET_DATE = jObject.get("date").toString();
			
			JSONArray jArray = new JSONArray(jObject.get("results").toString());
			JSONObject jaObject = jArray.getJSONObject(0);

			//当前城市
			NET_CITY = jaObject.get("currentCity").toString();
			NET_PM25 = jaObject.get("pm25").toString();
			
			//指数
			indexList.clear();
			JSONArray indexArray = new JSONArray(jaObject.get("index")
					.toString());
			for (int i = 0; i < indexArray.length(); i++) {
				JSONObject indexObject = indexArray.getJSONObject(i);
				IndexEntity index = new IndexEntity();
				index.setTitle(indexObject.get("title").toString());
				index.setZs(indexObject.get("zs").toString());
				index.setTipt(indexObject.get("tipt").toString());
				index.setDes(indexObject.get("des").toString());
				indexList.add(index);
			}
			

			//天气
			weatherList.clear();
			JSONArray weatherArray = new JSONArray(jaObject.get("weather_data")
					.toString());
			for (int i = 0; i < weatherArray.length(); i++) {
				JSONObject weatherObject = weatherArray.getJSONObject(i);
				WeatherEntity weather = new WeatherEntity();
				weather.setDate(weatherObject.get("date").toString());
				weather.setDayPictureUrl(weatherObject.get("dayPictureUrl")
						.toString());
				weather.setNightPictureUrl(weatherObject.get("nightPictureUrl")
						.toString());
				weather.setWeather(weatherObject.get("weather").toString());
				weather.setWind(weatherObject.get("wind").toString());
				weather.setTemperature(weatherObject.get("temperature")
						.toString());
				weatherList.add(weather);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return resultError;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics