我有一个Java数据结构,其从deserialising此JSON结果:避免嵌套地图的未经检查的铸件中的Java
{
'level1 value1': {
'level2 value1': {
'level3 value1': [ "25", "45", "78" ],
// ...
'level3 valueN': [ "59", "17", "42" ]
},
// ...
'level2 valueN': {
'level3 value1': [ "34", "89", "54" ],
// ...
'level3 valueN': [ "45", "23", "23" ]
},
},
// ...
'level1 valueN': {
// ...
}
}
在Java中,这变为:
Map<String, Map<String, Map<String, List<String>>>> data;
当然,数量级别是任意的,所以我不能在变量声明中嵌套集合。我在做什么,而不是是这样的:
void traverse(Map<String, ?> children) {
for (Map.Entry<String, ?> node : data.entrySet()) {
if (node.getValue() instanceof Map) {
doSomethingWithNonLeafNode((Map<String, Map<String, ?>>) node);
} else if (node.getValue() instanceof List) {
doSomethingWithLeafNode((Map <String, List<String>>) node);
}
}
}
void doSomethingWithNonLeafNode(Map <String, Map<String ?>> node) {
// do stuff
}
void doSomethingWithLeafNode(Map <String, List<String>> node) {
// do stuff
}
这显然是一个)使用一些未经检查的强制类型转换,和b)是丑陋的。我试图定义一个新类型来解决这个问题:
private interface Node extends Map<String, Map<String, ?>> {
}
private interface LeafNode extends Map<String, List<String>> {
}
// ...
if (node.getValue() instanceof Map) {
doSomethingWithNonLeafNode((Node) node);
} else if (node.getValue() instanceof List) {
doSomethingWithLeafNode((LeafNode) node);
}
然而,这给了我一个运行时异常:
java.lang.ClassCastException: java.util.HashMap cannot be cast to com.foo.ReportDataProcessor$Node
我怎样才能做到这一点在清洁,无警告的时尚?
是的,我认为“最不可能的”必须在这里赢得。我认为Java对于这类事情并不是最好的语言。 – 2012-03-14 14:44:31