String jsonStr = '{"menu": {' +
'"id": "file",' +
'"value": "File",' +
'"popup": {' +
'"menuitem": [' +
'{"value": "New", "onclick": "CreateNewDoc()"},' +
'{"value": "Open", "onclick": "OpenDoc()"},' +
'{"value": "Close", "onclick": "CloseDoc()"}' +
']' +
'}' +
'}}';
Đó JSON chuỗi thực sự là từ http://json.org/example.html. Đó là một trong những tốt nhất tôi có thể tìm thấy cho ví dụ này.
Bây giờ chúng ta đã có sẵn, hãy bắt đầu sử dụng JSONObject
. Bạn sẽ cần nhập khẩu sau đây để làm việc này: import org.json.JSONObject;
JSONObject jsonObj = new JSONObject(jsonStr);
Với instantiated, chúng ta có thể làm như sau để truy xuất phần khác nhau của dữ liệu từ chuỗi JSON -
// grabbing the menu object
JSONObject menu = jsonObj.getJSONObject("menu");
Reading =========> HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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();
result=sb.toString();=======>Here result is the json string
// these 2 are strings
String id = menu.getString("id");
String value = menu.getString("value");
// the popop is another JSON object
JSONObject popup = menu.getJSONObject("popup");
// using JSONArray to grab the menuitems from under popop
JSONArray menuitemArr = popupObject.getJSONArray("menuitem");
// lets loop through the JSONArray and get all the items
for (int i = 0; i < menuitemArr.length(); i++) {
// printing the values to the logcat
Log.v(menuitemArr.getJSONObject(i).getString("value").toString());
Log.v(menuitemArr.getJSONObject(i).getString("onclick").toString());
}
Đối với một ví dụ đơn giản bấm here
Nguồn
2012-07-20 12:52:48
Sử dụng HttpClient trên Android để trao đổi dữ liệu với máy chủ. Nếu bạn gặp khó khăn, hãy đăng mã của bạn và chúng tôi sẽ cố gắng trợ giúp. –