日期:2014-05-16  浏览次数:20277 次

android中JSON的使用

??? 在和网络信息交换时候采用JSON格式,在android中解析如下:

private void detectJSON() {
    	String str = "{"+
    	
		  "\"日期\" : \"2011-06-06\","+

		  //Like 是 JSONObject
		  "\"Like\" : {"+
		    "\"Name\" : \"加内特\","+
		    "\"Height\" : \"2.11cm\","+ 
		    "\"Age\" : 35"+
		  "},"+
		
		  //LikeList 就是一个 JSONObject
		  "\"LikeList\":" +
			  "{\"List\": " +
			  "["+
			  	  //这里也是JSONObject
				  "{"+
				    "\"Name\" : \"Rose\","+
				    "\"Height\" : \"190cm\","+ 
				    "\"Age\" : 23"+
				  "},"+
				  //这里也是JSONObject
				  "{"+
				    "\"Name\" : \"科比\","+
				    "\"Height\" : \"198cm\","+ 
				    "\"Age\" : 33"+
				  "}"+
			  "]"+
		      "}"+
	      "}";
    	
    	try {
			JSONObject dataJson = new JSONObject(str);
			Log.d(TAG, dataJson.getString("日期"));
			
			JSONObject nbaJson = dataJson.getJSONObject("Like");
		
			Log.d(TAG, nbaJson.getString("Name"));
			Log.d(TAG, nbaJson.getString("Height"));
			Log.d(TAG, nbaJson.get("Age").toString());
			
			JSONObject listJson = dataJson.getJSONObject("LikeList");
			JSONArray arrayJson = listJson.getJSONArray("List");
			
			for(int i=0;i<arrayJson.length();i++) {
				
				JSONObject tempJson = arrayJson.optJSONObject(i);
				
				Log.d(TAG, tempJson.getString("Name"));
				Log.d(TAG, tempJson.getString("Height"));
				Log.d(TAG, tempJson.getString("Age").toString());	
			}
			
			
		} catch (JSONException e) {
			System.out.println("Something wrong...");
			e.printStackTrace();
		}
    }

?