我有一个反序列化这个 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
}
这显然 a) 使用了一些未经检查的强制转换,并且 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
我怎样才能以干净、无警告的方式做到这一点?