Android อ่าน JSON


แค่ code snippet ของ android ในการอ่าน JSON เท่านั้นครับ
ลองดูละกันครับ

private void jsonTest() {
  String json = "{\"menu\": {"+
		"\"id\": \"file\","+
		  "\"value\": \"File\"," +
		  "\"popup\": {" +
		  "\"menuitem\": [" +
		  "      {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}," +
		  "      {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}," +
		  "      {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}" +
		  "    ]" +
		  "  }" +
		  "}}\";";
		try {
			JSONObject jsonO = new JSONObject(json);
			JSONObject menuObject = jsonO.getJSONObject("menu");
			String attId = menuObject.getString("id");
			String attValue = menuObject.getString("value");
			JSONObject attPopup = menuObject.getJSONObject("popup");
			JSONArray menuItemArray = attPopup.getJSONArray("menuitem");
			int lenght = menuItemArray.length();
			
			Log.d(TAG, "id:"+attId+" attValue:"+attValue);
			for(int i = 0;i< lenght; i++) {
				Log.d(TAG,"menu item, value:"+menuItemArray.getJSONObject(i).getString("value"));
				Log.d(TAG,"menu item, onClick:"+menuItemArray.getJSONObject(i).getString("onclick"));
				
			}
		} catch (JSONException e) {
			Log.d(TAG,"Json parsing error");
			e.printStackTrace();
		}
	}
Advertisements

One thought on “Android อ่าน JSON

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s