java 将 JSON 映射到列表<Map<<String, Object>>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44698437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Map JSON To List<Map<<String, Object>>
提问by Pranay Kumar
I have a JSON of the format
我有一个格式的 JSON
[{
"id" : "a01",
"name" : "random1",
"val" : "random2"
},
{
"id" : "a03",
"name" : "random3",
"val" : "random4"
}]
I need to map it to a List
holding various Map
objects. How do I achieve it?
我需要将它映射到一个List
持有各种Map
对象。我如何实现它?
Even if I am able to convert this JSON to a List
of String
of the form
即使我能这个JSON转换成List
的String
形式
{
"id" : "a01",
"name" : "random1",
"val" : "random2"
}
then I have a method to convert each individual String
to a Map
.
然后我有一种方法可以将每个人转换String
为Map
.
回答by Manos Nikolaidis
You will need to pass a TypeReference
to readValue
with the desired result type:
您将需要传递具有所需结果类型的TypeReference
to readValue
:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
回答by alexey28
Use gson with specified type to convert to list of maps:
使用指定类型的 gson 转换为地图列表:
Gson gson = new Gson();
Type resultType = new TypeToken<List<Map<String, Object>>>(){}.getType();
List<Map<String, Object>> result = gson.fromJson(json, resultType);