简体   繁体   English

尝试使用Jackson将JSON文件读入Map

[英]Trying to read a JSON file into a Map using Jackson

I have a JSON file with this structure... 我有一个具有这种结构的JSON文件...

{"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"}
{"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}

which doesn't have a key or commas separating each object. 没有键或逗号分隔每个对象。 So when I use this code... 所以当我使用这段代码时...

    File input = new File("test.json");
    ObjectMapper mapper = new ObjectMapper();
    Map obj = mapper.readValue(input, Map.class);

the obj variable only has the first line in the json file which makes sense as it doesn't know what the key is. obj变量仅在json文件中具有第一行,这是有意义的,因为它不知道键是什么。

I tried adding one by wrapping the objects like so... 我试图像这样包装对象来添加一个...

{ "Key": [

    {"id":"1","name":"name","categories":["category1","category2","category3"],"type":"store"},
    {"id":"2","name":"name","categories":["category1","category2","category3"],"type":"store"}
] }

including adding the commas to separate each as the file did not have any commas to separate them. 包括添加逗号分隔每个逗号,因为该文件没有任何逗号分隔。

While this works... 虽然这有效...

  1. I have multiple json files that I have to work with 我必须使用多个json文件
  2. The file sizes are a bit big so it takes a long time to add they "Key" wrap like I did in the example. 文件大小有点大,因此像我在示例中所做的那样,添加它们需要很长时间。

I'm hoping to avoid this altogether but not sure if I can. 我希望完全避免这种情况,但不确定是否可以。 Is there a way to read the json file using the original format into a Map so I can then filter the data as needed? 有没有一种方法可以使用原始格式将json文件读取到Map中,以便随后可以根据需要过滤数据?

There is a simple solution that doesn't require file modification. 有一个简单的解决方案,不需要修改文件。 Read your file line by line and then feed a single line to your ObjectMapper . 逐行读取文件,然后将一行输入到ObjectMapper You will get Many instances of Maps that you can store in a List, JsonArray or another map that you will need to create in your code. 您将获得许多Map实例,可以将它们存储在List,JsonArray或需要在代码中创建的其他地图中。 your code make look like: 您的代码如下所示:

ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object> list = new ArrayList<>()
try (
BufferedReader br = new BufferedReader(new FileReader(new File("test.json")))) {
String line;
while((line = br.readLine()) != null) {
  Map obj = mapper.readValue(line, Map.class);
  list.add(obj)
}

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

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