[英]How to safely retrieve ArrayList from Map<String, Object>
How do I safely retrieve an ArrayList object from Map where the value stored for the key is an ArrayList.如何从 Map 中安全地检索一个 ArrayList 对象,其中为键存储的值是一个 ArrayList。 Below is my code.
下面是我的代码。 Is there any other way to do it instead of the cast to ArrayList?
有没有其他方法可以代替对 ArrayList 的强制转换?
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("A"); list.add("B");
Map<String, Object> map = new HashMap<String, Object>();
map.put("list", list);
System.out.println(map.get("list").getClass()); // class java.util.ArrayList
List<String> l = (ArrayList<String>)map.get("list");
}
I was using the @JsonAnySetter
from Jackson
to store the Map<String, Object>
.我使用
Jackson
的@JsonAnySetter
来存储Map<String, Object>
。 When I checked the class they are of class java. util.ArrayList
当我检查课程时,它们属于
java. util.ArrayList
类java. util.ArrayList
java. util.ArrayList
. java. util.ArrayList
。 (Same exact situation as explained in the question). (与问题中解释的确切情况相同)。
After trying few things I was able to get it.在尝试了几件事之后,我能够得到它。 I know I am a bit late but hopefully, it will be helpful to someone in the future:
我知道我有点晚了,但希望这会对将来的人有所帮助:
I had the Map<String, Object>
the Object
was storing either another Map
, String
, or ArrayList
so I did the following things to get the values from my Map
.我有
Map<String, Object>
Object
正在存储另一个Map
、 String
或ArrayList
所以我做了以下事情来从我的Map
获取值。 You can use this as a reference and based on your required type you can do different things.您可以将其用作参考,并根据您需要的类型执行不同的操作。
public void marshal(Map<String, Object> extensions) {
for (Map.Entry<String, Object> property : extensions.entrySet()) {
if (property.getValue() instanceof ArrayList) {
for (Object dupItems : (ArrayList<String>) property.getValue()) {
if (dupItems instanceof Map) {
//do whatever you want to do Map type
} else if(dupItems instanceof String) {
//do whatever you want to do for String type
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.