gpt4 book ai didi

java - 找出 HashMap 中使用的类型

转载 作者:行者123 更新时间:2023-12-02 03:02:40 31 4
gpt4 key购买 nike

我有一个从 JSON 文件填充的 HashMap。键值对中的值可以是两种不同的类型 - 字符串或其他键值对。

例如:

HashMap<String,Object> hashMap = new Map();

JSON 文件看起来有点像这样:

    "custom": {
"mappedReference": {"source": "someMappedReference"},
"somethingElse": "some literal"
}
}

稍后,在填充 hashMap 后,当我迭代时,我需要检查该值是 HashMap 还是 String 类型。我尝试了多种方法,但似乎无法获取 map 中对象的类型。

    for(Map.Entry<String,Object> m : hashMap.entrySet())
{
final String key = m.getKey();
final Object value = m.getValue();

if(value instanceof Map<String,String>)
{
//get key and value of the inner key-value pair...
}
else
{
//it's just a string and do what I need with a String.
}

}

关于如何从 map 获取数据类型有什么想法吗?提前致谢

最佳答案

我发布了类似问题的答案:https://stackoverflow.com/a/42236388/7563898

这里是:

通常不赞成不必要地使用对象类型。但根据您的情况,您可能必须拥有 HashMap,尽管最好避免使用它。也就是说,如果您必须使用一个,这里有一小段代码可能会有所帮助。它使用instanceof。

Map<String, Object> map = new HashMap<String, Object>();

for (Map.Entry<String, Object> e : map.entrySet()) {
if (e.getValue() instanceof Integer) {
// Do Integer things
} else if (e.getValue() instanceof String) {
// Do String things
} else if (e.getValue() instanceof Long) {
// Do Long things
} else {
// Do other thing, probably want error or print statement
}
}

关于java - 找出 HashMap 中使用的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42227764/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com