如何将复杂的哈希图转换为arrayList

时间:2019-06-22 06:15:16

标签: java android json arraylist hashmap

我已将此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

1 个答案:

答案 0 :(得分:1)

您可以这样操作:创建一个具有数据成员String key和Bank value之类的类节点

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

}`

然后创建一个Node类的ArrayList,然后通过遍历here

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

来获取元素。