2013-04-15 64 views
1

我正在開發一個應用程序,當我用合適的參數擊中服務器時,得到的響應爲JSON。現在,我必須解析這些數據並將其存儲在arraylist中,我完成了這裏,但現在我必須根據JSONObject解析數據並存儲在array中。這是我想說的:以下是我得到的JSON response將JSON響應的值存儲在arraylist中,然後根據JSONObject輸出對其進行過濾

{"rewards":[ 
{ 
"rewardID":"2", 
"rewardType":"giftcard", 
"rewardTitle":"$5 Starbucks Gift Card" 
}, 
{ 
"rewardID":"3", 
"rewardType":"giftcard", 
"rewardTitle":"$5 Target Gift Card" 
}, 
{ 
"rewardID":"24", 
"rewardType":"miles", 
"rewardTitle":"100 AmericanAirlines Advantage Miles" 
}, 
{ 
"rewardID":"25", 
"rewardType":"miles", 
"rewardTitle":"100 US Airways Dividend Miles" 
} 
] 
} 

你可以看到rewardType參數已經得到了不同的價值觀像"giftcard""miles"。我必須分別根據JSONObject,即rewardType進行解析,並將其存儲在arraylist中作進一步處理。 下面是我在做什麼了越來越resposne並將其存儲在不同的變量:

@Override 
    protected String doInBackground(String... args) { 
     HttpParams params = new BasicHttpParams(); 
     params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, 
       HttpVersion.HTTP_1_1); 
     HttpClient httpClient = new DefaultHttpClient(params); 
     HttpPost post = new HttpPost(
       "API HERE"); 

     post.setHeader("Content-Type", "application/x-www-form-urlencoded"); 

     try { 
      post.setEntity(new StringEntity("client_id=" + client_id + "&" 
        + "client_secret=" + clientSecretKey, HTTP.UTF_8)); 

      HttpResponse response = httpClient.execute(post); 
      int i = response.getStatusLine().getStatusCode(); 
      System.out.println("HTTP Post status: " 
        + i); 

      BufferedReader in = new BufferedReader(new InputStreamReader(
        response.getEntity().getContent())); 

      // SB to make a string out of the inputstream 
      StringBuffer sb = new StringBuffer(""); 
      String line = ""; 
      String NL = System.getProperty("line.separator"); 
      while ((line = in.readLine()) != null) { 
       sb.append(line + NL); 
      } 
      in.close(); 

      // the json string is stored here 
      String result = sb.toString(); 
      System.out.println("Result Body: " + result); 
      return result; 

     } catch (Exception e) { 
      // TODO: handle exception 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     JSONObject jObject; 
     try { 
      jObject = new JSONObject(result); 

      JSONArray jSearchData = jObject.getJSONArray("rewards"); 

      for (int i = 0; i < jSearchData.length(); i++) { 

       JSONObject objJson = jSearchData.getJSONObject(i); 

       rewardID = objJson.getString("rewardID"); 
       rewardType = objJson.getString("rewardType"); 
       rewardTitle = objJson.getString("rewardTitle"); 

        if (rewardType == "giftcard") { 
        System.out.println("Reward ID: " + rewardID); 
        System.out.println("Reward Type: " + rewardType); 
        System.out.println("Reward Tittle: " + rewardTitle); 
        System.out.println("Reward ImageFileName: " 
          + rewardImageFilename); 
        System.out.println("Reward Price: " + rewardPrice); 
       } 

      } 

     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 

任何形式的幫助將不勝感激。

+0

現在你想要做 – Rohit

+0

見我對你的答案評論什麼。 – Anupam

+0

正如你所說我在做'rewardType ==「giftcard」'但是'if'語句裏面沒有打印任何內容。在'if'外面,我可以打印所有內容。如何只過濾那些有'rewardType = giftcard'作爲迴應的數據。 – Anupam

回答

1

用途:

如果(rewardType.equals( 「禮金券」))

+0

謝謝你的隊友,這個作品。 – Anupam

0

如果你從一個URL獲取這個數據,那麼這個

 HttpGet httpGet = new HttpGet(url); 
     HttpResponse httpResponse = httpClient.execute(httpGet); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
        inputstream = httpEntity.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(); 
     json = sb.toString(); 

否則

    try { 

     json = (your full data convert into string).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()); 
    } 



      rewards = jObj.getJSONArray("rewards"); 

     // looping through All 
     for (int i = 0; i < rewards.length(); i++) { 
      JSONObject c = rewards.getJSONObject(i); 

      // Storing each json item in variable 

      rewardID = c.getString("rewardID"); 
      rewardTitle = c.getString("rewardTitle"); 


      // adding all get values into array 
      if (rewardID != "null" && rewardTitle != "null") { 
      //add your data values into list and then filter 
       array1.add(rewardID); 
       array2.add(rewardTitle); 


      } 

     } 

編輯

ArrayList<String> array1 = new ArrayList<String>(); 
ArrayList<String> array2 = new ArrayList<String>(); 
    ArrayList<String> array3 = new ArrayList<String>(); 
    if (rewardType=="giftcard") { 
     array1.add(rewardID); 
     array2.add(rewardTitle); 
     array2.add(rewardType); 
     } 

    show in which activity you want to show 
+0

我只能用'rewardType = giftcard'在活動中顯示數據,其餘部分完成。 – Anupam

+0

正如你所看到的,我在回覆中有四個數據,其中有'rewardType = giftcard',兩個有'rewardType = miles'。我只想在我的活動中顯示具有'rewardType = giftcard'的數據。你能告訴我該怎麼做嗎? – Anupam

+0

簡單,如果條件檢查rewardType == giftcard然後添加數組列表中的整個事物或罪行物品,然後顯示在您的活動 – Rohit

0

你爲什麼不創建一個對象來封裝從JSON讀取數據。 IE:

public final class Reward { 
    private static final String REWARD_TYPE_GIFTCARD = "giftcard"; 
    private final int mRewardId; 
    private final String mRewardType; 
    private final String mRewardTitle; 

public Reward(final int rewardId, final String rewardType, final String rewardTitle){ 
    mRewardId = rewardId; 
    mRewardType = rewardType; 
    mRewardTitle = rewardTitle; 
} 
// Implement getter methods here. 

}

然後,您可以有這些獎勵的對象,這將讓他們稍微更容易使用的一個數組列表。你甚至可以添加一個檢查,如果獎勵是禮金券的方法:

public boolean isGiftcard() { 
    return REWARD_TYPE_GIFTCARD.equals(mRewardType); 
} 

此時你能做什麼羅希特建議,只有它,如果它是一個禮金券添加到列表中。最後,如果你仍然需要所有的對象,而你只是在尋找一種合乎邏輯的方式來組合它們,那麼嘗試一下HashMap>,其中鍵是獎勵類型,並且該值是一個列表,您可以將所有獎勵都設置爲Giftcard ()對於。

+0

你能告訴我如何使用不同的課程來實現這一點。我已經發布了我的代碼,無論我爲此做了什麼,只是過濾不會發生在我身上。 – Anupam

+0

既然你接受了另外一個答案,那麼我會假設你全部都已經設定好了嗎?我的回答確實只能幫助你清理代碼(我想我不明白你的實際問題)。 – natez0r

相關問題