参照此: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