简体   繁体   English

迭代Java中的hashmap列表

[英]iterate list of hashmap in java

I have one hashmap inside hashmap like 我在哈希图中有一个哈希图

List<Map> mapList = new ArrayList<Map>();
    for (int i = 0; i < 2; i++) {
        Map iMap = new HashMap();
        iMap.put("Comment", "");
        iMap.put("Start", "0");
        iMap.put("Max", "0");
        iMap.put("Min", "0");
        iMap.put("Price", "5000.00");
        iMap.put("DetailsID", "51");    
        mapList.add(iMap);
    }

    Map mMap = new HashMap();
    mMap.put("ID", "27");
    mMap.put("ParticipantID", "2");
    mMap.put("ItemDetails", mapList);

I want to iterate this map and put in JSONObject for that I do 我想迭代此地图并为此放入JSONObject

try {

    JSONObject object = new JSONObject();

    Iterator iterator = mMap.entrySet().iterator();     

    while (iterator.hasNext()) {
        Map.Entry mEntry = (Map.Entry) iterator.next();
        String key = mEntry.getKey().toString();            
        String value = mEntry.getValue().toString();
        object.put(key, value);

    }

    Log.v(TAG, "Object : " + object);

the response comes like 响应来像

Object : {"ItemDetails":"[{Price=5000.00, Comment=, DetailsID=51, Min=0, Max=0, StartViolation=0}, {Price=5000.00, Comment=, DetailsID=51, Min=0, Max=0, StartViolation=0}]","ID":"27","ParticipantID":"2"}

the inner list of hashmap is not iterating hashmap的内部列表没有迭代

the inner list of hashmap is not iterating hashmap的内部列表没有迭代

Indeed. 确实。 You haven't written any code to iterate over it. 您尚未编写任何代码对其进行迭代。 When you get the ItemDetails entry, you'll have a key of "ItemDetails" and a value which is the list. 当您获得ItemDetails条目时,将有一个"ItemDetails"键和一个值为列表的值。 Here's what you're then doing with those: 这就是您要处理的内容:

String key = mEntry.getKey().toString();            
String value = mEntry.getValue().toString();

So you're just calling toString() on the list. 因此,您只是在列表上调用toString() You need to work out what you really want to do. 您需要确定自己真正想做的事情。 For example, you might want: 例如,您可能想要:

if (mEntry.getValue() instanceof List) {
    // Handle lists here, possibly recursively
}

Note that you'll also probably want to recurse into each Map . 请注意,您可能需要递归到每个Map Again, you'll need to write code to do this. 同样,您将需要编写代码来执行此操作。 Basically, you can't assume that toString() is going to do what you need, which is the assumption you're making at the moment. 基本上,您不能假设toString()会做您需要的事情,这是您目前所做的假设。

try to do like this: 尝试这样做:

Set<Map.Entry<String, String>> entrySet = JSONObject.entrySet();
for (Entry entry : entrySet) {
    // your code
}
for (Map.Entry<String, String> entry : JSONObject.entrySet()) {
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM