Parsing JSON to custom ArrayList, only returning last item?

余生长醉 提交于 2019-12-23 05:11:38

问题


I'm finding this a bit odd, I'm parsing some JSON from a file in my /assets folder. I have set up a custom ArrayList. Now when I try and add data from the ArrayList to a listview, or a spinner (Same adapter) it only shows the last item. Here is my code:

My parsing method:

public ArrayList<ShopName> parseJSON(String json) {

    ArrayList<ShopName> shop = new ArrayList<>();
    ShopName item = new ShopName();

    Log.d(TAG, json);
    try {

        JSONArray jArray = new JSONArray(json);

        for (int i=0; i < jArray.length();i++) {
            JSONObject jObject = jArray.getJSONObject(i);
            item.setFromCurrency(jObject.getString("from"));
            item.setToCurrency(jObject.getString("to"));
            item.setRate(jObject.getString("cost"));
            data.add(item);
        }
    } catch (JSONException jen) {
        jen.printStackTrace();
    }
    return shop;
}

I'm not quite sure where my error is. Am I parsing it incorrectly, maybe, storing it incorrectly? I have a feeling it's my ArrayList but I'm sure what I should be doing to fix it, I've tried using different Adapters, and searching StackOverflow but they all have difference issues so it's hard to narrow now.

I would appreciate your help on this. Thank you.


回答1:


public ArrayList<Data> parseJSON(String json) {

    ArrayList<Data> data = new ArrayList<>();
    // Data item = new Data();  // Move this into for loop

    Log.d(TAG, json);
    try {

        JSONArray jArray = new JSONArray(json);

        for (int i=0; i < jArray.length();i++) {
            Data item = new Data();
            JSONObject jObject = jArray.getJSONObject(i);
            item.setFromCurrency(jObject.getString("from"));
            item.setToCurrency(jObject.getString("to:"));
            item.setRate(jObject.getString("rate"));
            data.add(item);
        }
    } catch (JSONException je) {
        Log.d(TAG, je.getMessage());
    }
    return data;
}



回答2:


You only initialize item object once, that's why. Move

Data item = new Data();

Into your for loop.




回答3:


You should create new Data object for each JSON array item.

public ArrayList<Data> parseJSON(String json) {

    // remove this    
    // Data item = new Data();  

   ...
    try {

        JSONArray jArray = new JSONArray(json);

        for (int i=0; i < jArray.length();i++) {
            // move it here
            Data item = new Data(); 
            ...
            data.add(item);
        }
    } catch (JSONException je) {
        Log.d(TAG, je.getMessage());
    }
    return data;
}


来源:https://stackoverflow.com/questions/29190012/parsing-json-to-custom-arraylist-only-returning-last-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!