问题
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