1

我正在开发一个应用程序,JSON当我使用正确的参数访问服务器时,我会得到响应。现在,我必须解析这些数据并将其arraylist存储arrayJSONObject. 这就是我想说的:以下是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"。我必须根据JSONObjectierewardType单独解析并将其存储在以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();
        }

任何形式的帮助将不胜感激。

4

3 回答 3

1

利用:

if (rewardType.equals("giftcard"))

于 2013-04-16T05:05:49.037 回答
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
于 2013-04-15T12:17:37.153 回答
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.

}

然后,您可以拥有这些 Reward 对象的数组列表,这将使它们更易于使用。您甚至可以添加一个方法来检查奖励是否是礼品卡:

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

此时,您可以按照 Rohit 的建议进行操作,仅当它是礼品卡时才将其添加到列表中。最后,如果您仍然需要所有对象并且您只是在寻找一种合乎逻辑的方式对它们进行分组,请尝试使用 HashMap>,其中键是奖励类型,值是一个列表,您可以在其中放置所有奖励,即礼品卡() 为真。

于 2013-04-15T13:44:30.320 回答