【问题标题】:how to convert complex hashmap to arrayList如何将复杂的hashmap转换为arrayList
【发布时间】:2019-11-04 20:59:12
【问题描述】:

我已将此 JSON 转换为 Hashmap

http://www.mocky.io/v2/5d0dc72d3400008c00ca4a62

我已经嵌套了 Hashmap,我想将其转换为 ArrayList

Map<String, Bank> stringBankMap = getValues();

我想从stringBankMap 获取所有数据并添加到列表中。我还希望哈希图的键也将作为指南导入列表中。

这里是银行类

public class Bank {
    private String guid;
    private String title;
    private long date;
    private String logo;
    private HashMap<String, HashMap<String, BankList>> list;
}

这里是 BankList 类

public class BankList {
    private double buy;
    private double sell;
    private String currency;
}

我尝试了什么

 for(Map.Entry<String, Bank> entry1 : stringBankMap.entrySet()) {
                Bank newBank = new Bank(entry1.getKey());
                Bank bank = entry1.getValue();
                newBank.setDate(bank.getDate());
                newBank.setLogo(bank.getLogo());
                newBank.setTitle(bank.getTitle());
                List<BankList> bankListList = new ArrayList<>();
                for(Map.Entry<String, HashMap<String, BankList>> entry2 : bank.getList().entrySet()) {
                    HashMap<String, BankList> map = entry2.getValue();
                    for (Map.Entry<String, BankList> entry3 : map.entrySet()) {
                        BankList newBankList = new BankList(entry3.getKey());
                        BankList bankList = entry3.getValue();
                        newBankList.setBuy(bankList.getBuy());
                        newBankList.setSell(bankList.getSell());
                        bankListList.add(newBankList);
                    }
                }
                bankArrayList.add(newBank);
            }

但我不明白为什么会出现异常

如果可以,请向我推荐其他算法

 java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to core.model.Bank

【问题讨论】:

  • 您在哪一行得到错误? Bank newBank = new Bank(entry1.getKey());?
  • 银行银行 = entry1.getValue();
  • 你能贴出有关如何填充 stringBankMap 的代码吗?
  • 它是使用 Jackson 转换器从 JSON 中解析出来的
  • 啊,好的。看看the first answer to this question。可能是杰克逊的问题。

标签: java android json arraylist hashmap


【解决方案1】:

你可以这样做:用数据成员字符串键和银行值创建一个类节点

`class Node{
String key;
Bank value;
Node(String k,Bank val){
    key=k;
    value=val;
}

}`

然后创建一个类 Node 的 ArrayList,然后通过像 here 那样遍历映射,将元素添加到列表中,如 [list name].add(new Node([pass key and value here])

然后您可以按所需顺序遍历列表并通过 [arraylist name].get(index).key 或 [arraylist name].get(index).value 获取您的元素

【讨论】:

    猜你喜欢
    • 2018-04-12
    • 2017-08-14
    • 2011-12-09
    • 2012-06-02
    • 1970-01-01
    • 2021-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多