參照此:How to parse JSON in Android你需要首先JSONParser類:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
然後宣告您在活動所需要的所有變量:
// URL,使請求 私有靜態String url =「http://www.yourjsonurl.com/json.php」;
// JSON節點名稱 private static final String TAG_CONTACTS =「contacts」; private static final String TAG_ID =「id」;私人靜態最終字符串TAG_NAME =「name」;
//聯繫人JSONArray JSONArray contacts = null;
然後:
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
}
} catch (JSONException e) {
e.printStackTrace();
}
通過通過基本訓練和一點在谷歌研究會,你應該能夠找出如何做到這一點?如果有的話,這個問題其實是很多的副本中,還有很多其他問題。 – 2Dee
可能重複的[如何在Android中解析JSON](http://stackoverflow.com/questions/9605913/how-to-parse-json-in-android) –
我強烈推薦[AndroidQuery](https:// code.google.com/p/android-query/)庫用於此目的以及許多其他目的 – ygesher