小编典典
这是我从URL解析json的代码:
public JSONObject getJSONFromUrl(String url) {
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
json = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jObj;
// 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());
}
Log.v("debug", "JSON ready to parsing");
return jObj;
}
public void parsingData(JSONObject json) {
try {
JSONArray data = json.getJSONArray("data");
for (int i = 0; i < data.length(); i++) {
// Do your stuff, example :
JSONObject c = data.getJSONObject(i);
JSONObject topDrops = c.getJSONObject("topDrops");
JSONArray playerArray = topDrops.getJSONArray("player");
// playerArray.getJSONObject(0) == first player
}
} catch (JSONException e) {
e.printStackTrace();
Log.v("debug", "Error during the connection HTTP");
cancel(Boolean.TRUE);
}
}
2020-07-27