简体   繁体   中英

A JSon Array - Format & Parsing

I have the following code for parsing json data in a file with Jackson.

   ObjectMapper mapper  = new ObjectMapper();
   JsonFactory jsonFactory = new JsonFactory();
   try(BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/foos.json")))) {
     Iterator<Foo> fooItr = mapper.readValues( jsonFactory.createParser(br), Foo.class);
     fooItr.forEachRemaining(System.out::println);        
   }catch(Exception ex){ .. }

don't work for a JSon array in a format as

[
  {...},
  {...}
]

but work for a format

  {...}
  {...}

What will be a proper parsing method for the JSon array format?

Pass List as Class rather than Foo Class where serializing using mapper

Try this --

        List<Foo> tempList = new ArrayList<>();
    
        JsonFactory jsonFactory = new JsonFactory();
       try(BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/foos.json")))) {
           tempList = mapper.readValues( jsonFactory.createParser(br), tempList.getClass());

 Iterator<Foo> fooItr  =  tempList.listIterator(); 
            fooItr.forEachRemaining(System.out::println);
        }catch(Exception ex){ .. }

I find a solution as the following

ObjectMapper mapper  = new ObjectMapper();
List<MyDataHolder> list = mapper.readValue(
  new InputStreamReader(getClass().getResourceAsStream("/foos.json")),
  new TypeReference<ArrayList<MyDataHolder>>() {});

the json data is in a file.

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