将 JSON 解析为自定义 ArrayList,只返回最后一项? [英] Parsing JSON to custom ArrayList, only returning last item?
问题描述
我觉得这有点奇怪,我正在从/assets 文件夹中的文件解析一些 JSON.我已经设置了一个自定义的 ArrayList.现在,当我尝试将 ArrayList 中的数据添加到列表视图或微调器(相同的适配器)时,它只显示最后一项.这是我的代码:
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:
我的解析方法:
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;
}
我不太确定我的错误在哪里.我是否错误地解析它,也许,错误地存储它?我有一种感觉,这是我的 ArrayList,但我确定我应该怎么做来修复它,我尝试使用不同的适配器,并搜索 StackOverflow,但它们都有不同的问题,所以现在很难缩小范围.
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.
推荐答案
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;
}
这篇关于将 JSON 解析为自定义 ArrayList,只返回最后一项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!