简体   繁体   中英

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet

I have following piece of code :

JsonObject json = (JsonObject) attVal;
HashSet<Map.Entry<String,JsonElement>> map = (HashSet<Map.Entry<String, JsonElement>>) json.entrySet();

I am getting below exception at line 2:

java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.HashSet

My json input is: {"key":"4e32cd954f31320078c5fd218110c7ca","number":"","unique_key":"001"}

What is the reason and how to solve this?

HashMap$EntrySet has nothing common with HashSet and because of this casting fails

You should rather iterate over json's entry set and add following values to your HashSet

HashSet<Map.Entry<String,JsonElement>> map = new HashSet<>();

for(Map.Entry<String,JsonElement> entry : json.entrySet()){
    if(entry != null) {
        map.put(entry.getKey(), jsonObject.get(entry.getKey()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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