我正在开发一个应用程序,JSON
当我使用正确的参数访问服务器时,我会得到响应。现在,我必须解析这些数据并将其arraylist
存储array
在JSONObject
. 这就是我想说的:以下是JSON response
我得到的:
{"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
ierewardType
单独解析并将其存储在以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();
}
任何形式的帮助将不胜感激。