简体   繁体   English

将具有多个对象的json文件读取到地图Java中

[英]Read json file with multiple objects into a map java

Note: Before posting this here, I spent a chunk of time trying to look for a solution about this here, but couldn't find any. 注意:在此处发布此内容之前,我花了很多时间试图在此处查找有关此问题的解决方案,但找不到任何解决方案。

I have this JSON file that contains multiple json objects that I want to read into a map, each object is of the format {"key1":"value1", "key2":"value2"} , I tried 我有这个JSON文件,其中包含多个我想读取到地图中的json对象,每个对象的格式均为{"key1":"value1", "key2":"value2"} ,我尝试了

Map<String, String> map = MAPPER.readValue(fixture("fixtures/file_name.json"), new TypeReference<Map<String, String>>() {});

as that worked for reading a file into a map of map of list ( Map<String, Map<String, List<String>>> ). 就像将文件读入列表列表Map<String, Map<String, List<String>>>Map<String, Map<String, List<String>>> )一样。 Is there something that should be different? 有什么不一样的吗?

My .json file looks like 我的.json文件看起来像

[
   {"key1":"value1_1", "key2":"value2_1"},
   {"key1":"value1_2", "key2":"value2_2"},
   ...
]

I have also another json file that I want to read into a map, that looks like 我还有另一个要读入地图的json文件,看起来像

[
   "key1": {
       "key1_1": [
           {"key1_1_1":"value1", "key1_1_2":"value2"},
           ...
       ],
       ...
    },
    "key2":<int>,
    "key3":{
        "key3_1":[],
        ...
    },
    ...
    "key_n":<string>,
    ...
]

Can you help me map those files correctly, without writing too many lines of code? 您能帮我正确地映射那些文件,而无需编写过多的代码行吗?

As you are handling different cases of nested objects varying from Strings to JsonArrays it would be good to implement your map as Map<String, Object> . 在处理从Strings到JsonArrays的嵌套对象的不同情况时,最好将地图实现为Map<String, Object>

Follow the below implementation, 遵循以下实现,

ObjectMapper mapper = new ObjectMapper();
MapType type = mapper.getTypeFactory().constructMapType(
    Map.class, String.class, Object.class);
Map<String, Object> data = mapper.readValue(jsonString, type);

Here I am reading the JSON as a string. 在这里,我将JSON读取为字符串。 You can change your implementation to accommodate file reading as well. 您可以更改实现以适应文件读取。

I would suggest you to use the Jackson library. 我建议您使用Jackson库。

Here is a mkyong tutorial 这是一个mkyong教程

Just change the code to 只需将代码更改为

Map map = mapper.readValue(new File("c:\\whatever.json"), Map.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM