2017-10-21 88 views
0

我有我想分析的JSON代碼的片段:基本上我想存儲「有效時間」和「目的」,你可以看到裏面的「結果」json數組使用Java Android Studio),但我很努力,因爲這是我第一次處理JSON。JSON Array解析多個數組

{ 
     "results": [ 
     { 
      "effective_time": "20121114", 
      "inactive_ingredient": [ 
      "Inactive ingredients *acetylated monoglycerides, *anhydrous lactose, *carnauba wax, colloidal silicon dioxide,*corn starch, *croscarmellose sodium, D&C Yellow #10 Aluminum Lake, FD&C Yellow #6 Aluminum Lake, hypromellose, *hypromellose phthalate, *iron oxide Yellow (iron oxide ochre), methacrylic acid copolymer, microcrystalline cellulose, *mineral oil, *polyethylene glycol (PEG)-400, *polysorbate 80, povidone, pregelatinized starch, *propylene glycol, *simethicone, silicon dioxide, sodium bicarbonate, sodium hydroxide, sodium lauryl sulfate, starch, stearic acid, talc, titanium dioxide, triacetin, and triethyl citrate. *May also contain." 
      ], 
      "purpose": [ 
      "Purpose Pain reliever" 
      ], 
      "keep_out_of_reach_of_children": [ 
      "Keep out of reach of children In case of overdose, get medical help or contact a Poison Control Center right away." 
      ] 
       ... 
       ... 
     } 
     ] 
} 

這是我到目前爲止的代碼

String drugDescription="no description"; 
try{ 
    JSONObject jsonQueryResult = new JSONObject(JSONFILE); 
     JSONArray jsonResultArray = jsonQueryResult.getJSONArray("result"); 
     JSONObject jsonDrugDescription = jsonResultArray.getJSONObject(0); 
     drugDescription = jsonDrugDescription.toString(); 
} 
catch(JSONException e){ 
     e.printStackTrace(); 
} 
searchResultTextView.setText(drugDescription); 

drugDescription仍呈現 「無說明」

感謝您的幫助!

+0

檢查您是否獲得在catch塊中的任何異常。在你的catch塊中放入一條日誌語句。 – Srijith

回答

0

如果你是新手,你應該通過一些關於Json解析here的教程。

用於獲取effective_timepurpose你可以做:

try { 
     JSONObject jsonObject = new JSONObject(json); 
     JSONArray firstResult = jsonObject.getJSONArray("results"); 
     if (firstResult != null && firstResult.length() > 0) { 
      for (int i=0; i<firstResult.length(); i++) { 
       JSONObject result = firstResult.getJSONObject(i); 
       // This is your effective_time; 
       String effective_time = result.getString("effective_time"); 
       JSONArray purpose = result.getJSONArray("purpose"); 
       if (purpose != null && purpose.length() > 0) { 
        for (int j=0; j<purpose.length(); j++) { 
         // This is the purpose; 
         String purposeData = purpose.getString(j); 
        } 
       } 
      } 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
} 
+0

我在發佈之前嘗試過類似的東西,但它不起作用 –

+0

然後你可能沒有發佈的json。 –

+0

就是這樣,因爲如果我試着用jsonarray開始的json的其他部分,我可以使它工作;它正在訪問結果數組,讓我掙扎 –