将JSON响应的值存储在arraylist中,然后根据JSONObject输出过滤它们

时间:2013-04-15 12:13:13

标签: android json arraylist

我正在开发一个应用程序,当我使用适当的参数访问服务器时,我得到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"等不同的值。我必须分别根据JSONObjectrewardType进行解析,并将其存储在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();
        }

任何形式的帮助都将受到赞赏。

3 个答案:

答案 0 :(得分:1)

使用:

if(rewardType.equals(“giftcard”))

答案 1 :(得分:0)

如果您从网址获取此数据,那么

      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

答案 2 :(得分: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);
}

此时你可以做Rohit建议的事情,只有当它是礼品卡时才将其添加到列表中。最后,如果您仍然需要所有对象,并且您只是在寻找一种合理的方式来对它们进行分组,请尝试使用HashMap&gt;其中键是奖励类型,值是一个列表,其中您放置了isGiftcard()的所有奖励。