简体   繁体   中英

Trying to read a JSON file into a Map using Jackson

I have a JSON file with this structure...

{"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.

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
  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?

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 . 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. 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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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