1. 程式人生 > >java 解析json, 帶轉義字元的json

java 解析json, 帶轉義字元的json

一:解析普通json

      1:不帶轉化字元

       格式{"type":"ONLINE_SHIPS","message":{"currentTime":1400077615368,"direction":0,"id":1,"latitude":29.5506,"longitude":106.6466}}

JSONObject jsonObject = new JSONObject(jsonstr).getJSONObject("message");
					System.out.println("currentTime:"+jsonObject.get("currentTime"));	
					System.out.println("direction:"+jsonObject.get("direction"));	
					System.out.println("latitude:"+jsonObject.get("latitude"));	
					System.out.println("longitude:"+jsonObject.get("longitude"));

      jsonarray    

JSONObject jo = ja.getJSONArray("cargoList").getJSONObject(0);

    2:帶轉義字元的json格式

    {"type":"ONLINE_SHIPS","message":"{\"currentTime\":1400077615368,\"direction\":0,\"id\":1,\"latitude\":29.5506,\"longitude\":106.6466}"}

     其實也很簡單,先把它轉化成字串就可以了

JSONObject jsonObject = new JSONObject(jsonstr);
					//先通過字串的方式得到,轉義字元自然會被轉化掉
					String jsonstrtemp = jsonObject.getString("message");										
					System.out.println("message:"+jsonstrtemp);	
					jsonObject = new JSONObject(jsonstrtemp);
					System.out.println("currentTime:"+jsonObject.get("currentTime"));	
					System.out.println("direction:"+jsonObject.get("direction"));	
					System.out.println("latitude:"+jsonObject.get("latitude"));	
					System.out.println("longitude:"+jsonObject.get("longitude"));



二:遍歷Json物件

JSONObject ports = ja.getJSONObject("ports");
				Iterator<String> keys = ports.keys();
				while(keys.hasNext()){  
		           String key=keys.next();  
		           String value = ports.getString(key);
		        }