0

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?

Rainbow
  • 61
  • 1
  • 7
  • `[ {}, {} ]` is an array... `{} {}` is not. You need to parse the file into a `List`, not a `Foo` itself – OneCricketeer Oct 23 '20 at 17:09
  • @OneCricketeer The code parses the data into an iterator, but not a single object/entity. – Rainbow Oct 23 '20 at 17:24
  • Okay, well, [as shown here](https://stackoverflow.com/questions/6349421/how-to-use-jackson-to-deserialise-an-array-of-objects), you have other options. Otherwise, you should edit the post to include the errors you are getting – OneCricketeer Oct 23 '20 at 17:46

2 Answers2

0

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){ .. }
Ayush v
  • 351
  • 2
  • 9
  • That doesn't work, unfortunately. The returned type is MappingIterator which isn't Iternator nor List. A class cast can make it compiled, but will cause a running error. – Rainbow Oct 24 '20 at 04:46
  • assigning it to a list variable and then get the iterator from the list should work. Updated the example – Ayush v Oct 24 '20 at 06:00
0

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.

Rainbow
  • 61
  • 1
  • 7