2012-03-07 50 views
51

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

+2

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

+0

http://stackoverflow.com/a/2840873/643350 – Dipin

+0

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. –

Trả lời

3

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.

+0

Xin chào, tôi đã đặt lỗi này nhưng nhận được lỗi tôi đã nhập mọi thứ nhưng vẫn gặp sự cố – iamlukeyb

+0

Bạn cần phải bao bọc khối mã ở trên để thử, tôi đã chỉnh sửa mã để phản ánh điều này. – Ljdawson

+0

Bạn vẫn gặp sự cố? – Ljdawson

111

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 
    } 
} 
+0

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

9
  1. 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; 
    
        } 
    } 
    
  2. 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(); 
} 
0

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

+0

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

Các vấn đề liên quan