将JSON解析为自定义ArrayList,仅返回最后一项? [英] Parsing JSON to custom ArrayList, only returning last item?

查看:117
本文介绍了将JSON解析为自定义ArrayList,仅返回最后一项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这有点奇怪,我从/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆