Tôi có thể tìm hướng dẫn từng bước về cách phân tích nguồn cấp dữ liệu JSON trong Android ở đâu? Tôi chỉ là một người mới bắt đầu Android muốn học.Cách phân tích cú pháp JSON trong Android
Trả lời
Tôi đã mã hóa một ví dụ đơn giản cho bạn và chú thích nguồn. Ví dụ cho thấy làm thế nào để lấy json sống và phân tích thành một JSONObject cho khai thác chi tiết:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Một khi bạn đã JSONObject bạn tham khảo các SDK biết chi tiết về làm thế nào để trích xuất các dữ liệu bạn yêu cầu.
Android có tất cả các công cụ bạn cần để phân tích cú pháp json tích hợp sẵn. Ví dụ sau, không cần GSON hay bất cứ thứ gì như thế.
Nhận JSON của bạn:
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(http://someJSONUrl/jsonWebService);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
bây giờ bạn có JSON của bạn, vì vậy những gì?
Tạo một JSONObject:
JSONObject jObject = new JSONObject(result);
Để có được một chuỗi cụ thể
String aJsonString = jObject.getString("STRINGNAME");
Để có được một cụ boolean
boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME");
Để có được một số nguyên cụ thể
int aJsonInteger = jObject.getInt("INTEGERNAME");
Để có được một cụ dài
long aJsonLong = jObject.getBoolean("LONGNAME");
Để có được một cụ thể đôi
double aJsonDouble = jObject.getDouble("DOUBLENAME");
Để có được một cụ JSONArray:
JSONArray jArray = jObject.getJSONArray("ARRAYNAME");
Để có được các mục từ mảng
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String oneObjectsItem = oneObject.getString("STRINGNAMEinTHEarray");
String oneObjectsItem2 = oneObject.getString("anotherSTRINGNAMEINtheARRAY");
} catch (JSONException e) {
// Oops
}
}
Cũng có thể có trường hợp khi bạn nhận được một JSONArray và nếu bạn cố gắng JSONObject jObject = new JSONObject (kết quả) - bạn sẽ nhận được một ngoại lệ về phân tích cú pháp. Trong trường hợp này JSONArray jArray = new JSONArray (kết quả) sẽ hoạt động. – Stan
Viết JSON Parser Lớp
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; } }
Parsing JSON dữ liệu Khi bạn tạo lớp phân tích cú pháp tiếp theo thi ng là biết cách sử dụng lớp đó. Dưới đây tôi giải thích cách phân tích cú pháp json (được lấy trong ví dụ này) bằng cách sử dụng lớp trình phân tích cú pháp.
2.1.Lưu trữ tất cả các tên nút này trong các biến: Trong các liên hệ json chúng ta có các mục như tên, email, địa chỉ, giới tính và số điện thoại. Điều đầu tiên là lưu trữ tất cả các tên nút này trong các biến. Mở lớp hoạt động chính của bạn và khai báo lưu trữ tất cả các tên nút trong các biến tĩnh.
// url to make request
private static String url = "http://api.9android.net/contacts";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
2.2. Sử dụng lớp trình phân tích cú pháp để lấy JSONObject và lặp qua từng mục json. Dưới đây tôi đang tạo một thể hiện của lớp JSONParser và sử dụng vòng lặp i am looping qua từng mục json và cuối cùng lưu trữ mỗi dữ liệu json trong biến.
// 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);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
Hãy thử làm theo hướng dẫn này http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ Hy vọng điều này sẽ giúp bạn bắt đầu với JSONParsing
Tôi đã thử mẫu từ Android Hive (http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) ....... Nhưng tác giả của trang web có một số lỗi chính tả trong nó ... nhưng nó là một nơi tuyệt vời để học lập trình Android cho người mới bắt đầu ... cảm ơn cho nguồn! – Devrath
- 1. Phân tích cú pháp JSON trong Android
- 2. Cách phân tích cú pháp chuỗi json trong Android?
- 3. Cách phân tích cú pháp JSON Array này trong android
- 4. Cách phân tích cú pháp JSON (AS3)
- 5. Phân tích cú pháp JSON trong Python
- 6. phân tích cú pháp json trong haskell
- 7. JSONKit phân tích cú pháp chuỗi json
- 8. Hive: phân tích cú pháp JSON
- 9. Phân tích cú pháp JSON với Dart
- 10. phân tích cú pháp json python
- 11. Lỗi phân tích cú pháp JSON
- 12. Kết hợp phân tích cú pháp phân tích cú pháp, phân tích cú pháp và phân tích cú pháp rừng
- 13. Bộ nhớ trong của Android, cách phân tích cú pháp đúng cách tệp văn bản JSON
- 14. Phân tích cú pháp không phân tích cú pháp đúng cách ("href") trong IE
- 15. Javascript cách phân tích cú pháp mảng JSON
- 16. Nhận và phân tích cú pháp JSON trong Actionscript
- 17. Phân tích cú pháp JSON API trong C#
- 18. Phân tích cú pháp tệp JSON lớn trong Nodejs
- 19. phân tích cú pháp đầu vào json trong hadoop java
- 20. Trình phân tích cú pháp JSON trong PascalScript
- 21. Phân tích cú pháp JSON trong ANSI C
- 22. Phân tích cú pháp Json trong Blackberry 5.0
- 23. MongoDB + Java - phân tích cú pháp JSON qua com.mongodb.util.JSON.parse
- 24. Phân tích cú pháp JSON với .NET 2.0
- 25. Phân tích cú pháp một mảng JSON thành một NSDictionary
- 26. XStream phân tích cú pháp JSON không có nút gốc
- 27. Phân tích cú pháp JSON từ Bảng tính Google
- 28. JSON tới trình phân tích cú pháp Groovy
- 29. Phân tích cú pháp JSON dung sai lỗi
- 30. Trình phân tích cú pháp JSON tốt nhất cho Qt?
có một phân tích cú pháp JSON nhúng trong sdk. xem http://developer.android.com/reference/org/json/package-summary.html – njzk2
http://stackoverflow.com/a/2840873/643350 – Dipin
Xem qua tất cả các liên kết ** Liên quan ** trên phía bên phải - có _ton_ các câu hỏi tương tự. Chúng tôi đánh giá cao một chút nỗ lực trước khi đặt câu hỏi. –