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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:18:20  来源:igfitidea点击:

Map JSON To List<Map<<String, Object>>

javajsonHymansonobjectmapper

提问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 Listholding various Mapobjects. How do I achieve it?

我需要将它映射到一个List持有各种Map对象。我如何实现它?

Even if I am able to convert this JSON to a Listof Stringof the form

即使我能这个JSON转换成ListString形式

{
    "id" : "a01",
    "name" : "random1",
    "val" : "random2"

}

then I have a method to convert each individual Stringto a Map.

然后我有一种方法可以将每个人转换StringMap.

回答by Manos Nikolaidis

You will need to pass a TypeReferenceto readValuewith the desired result type:

您将需要传递具有所需结果类型的TypeReferenceto 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);