我正在開發一個應用程序,當我用合適的參數擊中服務器時,得到的響應爲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();
}
任何形式的幫助將不勝感激。
現在你想要做 – Rohit
見我對你的答案評論什麼。 – Anupam
正如你所說我在做'rewardType ==「giftcard」'但是'if'語句裏面沒有打印任何內容。在'if'外面,我可以打印所有內容。如何只過濾那些有'rewardType = giftcard'作爲迴應的數據。 – Anupam