1、解析JSON數據:android
首先引入包import org.json.JSONObject;(android sdk 14之後應該自帶了 )json
Android端的程序解析JSON和JSON數組:數組
package com.example.helloandroid; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; public class JSONActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_json); //JSON 解析 String strJson = "{\"sid\":\"2\",\"name\":\"張三\"}"; try { JSONObject userObject = new JSONObject(strJson); String name = userObject.getString("name"); Toast.makeText(JSONActivity.this, name, 1000).show(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //JSON 數組解析 String strArrayJson = "[{\"sid\":\"1\",\"name\":\"張三\"},{\"sid\":\"2\",\"name\":\"張四\"}]"; JSONArray userJsonArray; try { userJsonArray = new JSONArray(strArrayJson ); for(int i=0;i<userJsonArray.length();++i){ JSONObject userJObject = (JSONObject) userJsonArray.get(i); String name = userJObject.getString("name"); Toast.makeText(JSONActivity.this, name, 1000).show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }