考虑以下 JSON:
[
{
"map": "TEST",
"values": [
"test",
"test2"
]
},
{
"map": "TEST1",
"values": [
"test",
"test3",
"test4"
]
},
{
"map": "TEST2",
"values": [
"test4",
"test2",
"test5",
"test2"
]
}
]
已由 getResourceAsString 函数加载到字符串中。 如何制作一个 HashMap,其中我的键是“map”字段,而我的值是“values”字段数组? 我在其他类似问题中尝试了很多解决方案,但没有任何效果。
这是我的代码的开头:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
但我不知道如何将它分配给 Map,readValue 方法似乎没有给出正确的东西
最佳答案
您可以将其反序列化为 List<Map<String, Object>>
然后转换为 Map
:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./src/main/resources/test.json");
ObjectMapper mapper = new ObjectMapper();
TypeReference rootType = new TypeReference<List<Map<String, Object>>>() { };
List<Map<String, Object>> root = mapper.readValue(jsonFile, rootType);
Map<String, Object> result = root.stream()
.collect(Collectors.toMap(
m -> m.get("map").toString(),
m -> m.get("values")));
System.out.println(result);
}
}
上面的代码打印:
{TEST2=[test4, test2, test5, test2], TEST=[test, test2], TEST1=[test, test3, test4]}
关于java - 将 JSON 字符串映射到 HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589691/