【发布时间】:2020-01-03 13:43:06
【问题描述】:
所以我目前正在尝试将 json 文件转换为 java 地图。我只是使用以下代码,它可以正常工作:
ObjectMapper mapper = new ObjectMapper();
try {
Map<String, Object> map = mapper.readValue(new File(
"res/cache.json"), new TypeReference<Map<String, Object>>() {
});
} catch (Exception e) {
e.printStackTrace();
}
但是,问题是我不希望地图的类型为Map<String, Object>,而是Map<String, NodeType>,我在其中创建了一个新的静态类,如下所示。
static class NodeType {
// A map of all the nodes, for example '{0001 : node, 0002 : anotherNode}'
public Map<String, Node> nodes; //Note: Node is another static class containing a map of values.
public NodeType() {
nodes = new HashMap<>();
}
}
我的解决方案是将new TypeReference<Map<String, Object>> 替换为new TypeReference<Map<String, NodeType>>,但我目前收到一个错误,即json 和类的结构不完全匹配。为了尝试解释,该类将每个变量作为 json 中的键/值,然后将映射作为另一个键/值映射。
有谁知道我如何“扁平化” NodeType 类以使两个结构匹配。
谢谢。
Json 文件内容:
{
"areas" : {
"0001" : {
"lightsOn" : false,
"volume" : 30,
"musicPlaying" : true,
"videoPlaying" : false
},
"0002" : {
"lightsOn" : false,
"volume" : 15,
"musicPlaying" : true,
"videoPlaying" : false
},
"0003" : {
"lightsOn" : true,
"volume" : 60,
"musicPlaying" : true,
"videoPlaying" : false
}
},
...
}
补充一点,当我通过 Object Mapper 解析 NodeType 类时,我得到了这个:
{
"nodes" : {
"0002" : {
"states" : {
"volume" : 15,
"musicPlaying" : true,
"lightsOn" : false,
"videoPlaying" : false
}
},
"0003" : {
"states" : {
"volume" : 60,
"musicPlaying" : true,
"lightsOn" : true,
"videoPlaying" : false
}
},
"0001" : {
"states" : {
"volume" : 30,
"musicPlaying" : true,
"lightsOn" : false,
"videoPlaying" : false
}
}
}
}
编辑:我觉得我可能在本教程的正确轨道上 - https://www.baeldung.com/jackson-map
【问题讨论】:
-
在我看来,您要做的仍然是尝试将JSON字符串转换为嵌套的
Map。那么new TypeReference<Map<String, Object>>有什么问题呢?
标签: java json dictionary