【发布时间】:2020-09-01 06:19:00
【问题描述】:
我一直在尝试实现一种从 JSON 文件中读取嵌套 ArraList 的方法,但没有成功。
我的 JSON 文件具有以下结构:
{
"INT": {
"Company": "mock company",
"id": "0123456789X",
"IntegerForm" : [1, 5, 7, 10],
"StringForm": ["string 1", "string 2", "string 3"],
"NestedMap" : {
"key1" : "value1",
"key2" : "value2"
}
},
"TEST": {
"Company": "mock company",
"id": "0123456789X",
"IntegerForm" : [1, 5, 7, 10],
"StringForm": ["string 1", "string 2", "string 3"],
"NestedMap" : {
"key1" : "value1",
"key2" : "value2"
} },
"PRE": {
"Company": "mock company",
"id": "0123456789X",
"IntegerForm" : [1, 5, 7, 10],
"StringForm": ["string 1", "string 2", "string 3"],
"NestedMap" : {
"key1" : "value1",
"key2" : "value2"
}
}
}
我有几个级别的嵌套地图,我可以使用以下类读取它们:
public class JSONMapper {
private HashMap<?, ?> jsonMap;
public JSONMapper(String jsonPath) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
jsonMap = objectMapper.readValue(new File(jsonPath), HashMap.class);
}
public HashMap<?, ?> getJsonMap(String key) {
return (HashMap<?,?>)jsonMap.get(key);
}
}
要读取嵌套地图,我只需将它们转换如下:
HashMap<?, ?> dataMap;
JSONMapper mapper;
mapper = new JSONMapper("src/test/resources/datatest/example.json");
dataMap = mapper.getJsonMap("TEST");
HashMap <String, HashMap<String, String>> = (HashMap <String, HashMap<String, String>>) dataMap.get("NestedMap")
如何实现类似的方法来分别读取 IntegerForm 和 StringForm 作为 List 和 List 的值? 我想做类似的事情
new ArrayList ((List<Integer>) mapper.getJSONArray("IntegerForm"))
【问题讨论】:
标签: json list dictionary arraylist jackson