2012-03-07 33 views
51

從哪裏可以找到關於如何在Android中解析JSON訂閱源的分步說明?我只是一個想學習的Android初學者。如何解析Android中的JSON

+2

有嵌入SDK中的JSON解析器。請參閱http://developer.android.com/reference/org/json/package-summary.html – njzk2 2012-03-07 17:01:49

+0

http://stackoverflow.com/a/2840873/643350 – Dipin 2012-03-07 17:05:22

+0

查看所有**相關**鏈接右邊 - 有類似的問題。在提出問題之前,我們感謝了一些努力。 – 2012-03-07 17:08:46

回答

3

我已經爲你編碼了一個簡單的例子並註明了源碼。這個例子說明如何搶活JSON和解析成一個JSONObject的細節提取:

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(); 
} 

一旦你有你的JSONObject參考SDK關於如何提取所需要的數據的詳細信息。

+0

嗨,我已經把這個,但得到的錯誤,我已經導入了一切,但仍然出現問題 – iamlukeyb 2012-03-07 17:18:04

+0

你將需要包裝上面的代碼塊在try-catch,我編輯代碼來反映這一點。 – Ljdawson 2012-03-07 17:22:34

+0

仍有問題? – Ljdawson 2012-03-07 17:36:11

111

Android擁有解析json內置所需的全部工具。示例如下,不需要GSON或類似的東西。

讓您的JSON:

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){} 
} 

現在你有你的JSON,還等什麼?

創建JSONObject

JSONObject jObject = new JSONObject(result); 

爲了得到一個特定的字符串

String aJsonString = jObject.getString("STRINGNAME"); 

爲了得到一個特定的布爾

boolean aJsonBoolean = jObject.getBoolean("BOOLEANNAME"); 

爲了得到一個特定的整數

int aJsonInteger = jObject.getInt("INTEGERNAME"); 

爲了得到一個專用的長

long aJsonLong = jObject.getBoolean("LONGNAME"); 

爲了得到一個特定的雙

double aJsonDouble = jObject.getDouble("DOUBLENAME"); 

爲了得到一個特定JSONArray

JSONArray jArray = jObject.getJSONArray("ARRAYNAME"); 

從數組

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

當你收到一個JSONArray並且如果你嘗試JSONObject jObject = new JSONObject(result)時,你也可能會遇到一種情況 - 你會得到一個關於解析的解釋。在這種情況下JSONArray jArray =新的JSONArray(結果)將工作。 – Stan 2013-02-18 19:33:39

9
  1. 寫作JSON解析器類

    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. 解析JSON數據 一旦你創建解析器類弄的項目接下來呢ng是要知道如何使用這個類。下面我解釋如何使用解析器類來解析json(在這個例子中)。

2.1。將所有這些節點名稱存儲在變量中:在聯繫人json中,我們有諸如姓名,電子郵件,地址,性別和電話號碼之類的項目。所以首先是將所有這些節點名稱存儲在變量中。打開主要活動類並聲明將所有節點名稱存儲在靜態變量中。

// 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。使用解析器類來獲取JSONObject並循環遍歷每個json項目。下面我創建JSONParser類的一個實例,並使用循環我循環通過每個JSON項目,並最終將每個JSON數據存儲在變量中。

// 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

嘗試下面這個教程http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ 希望這將幫助你開始JSONParsing

+0

我試過從Android Hive的示例(http://www.androidhive.info/2012/01/android-json-parsing-tutorial/).......但該網站的作者有一些錯字錯誤它...但它是學習android編程初學者的好地方...感謝源碼! – Devrath 2013-07-01 05:38:31