To reduce memory consumption we will use gson library. Import com.google.gson.Gson;
DOCUMENTATION: https://github.com/google/gson
MAVEN DEPENDENCY: https://search.maven.org/artifact/com.google.code.gson/gson/2.8.9/jar
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
Gson is an open-source Java library to serialize and deserialize Java objects to JSON
Using gson we can navigate through JSON objects and nested objects and iteratively convert them into java Objects.
private void readLargeJson(String path) throws IOException {
try ( InputStream inputStream = Files.newInputStream(Path.of(path));
JsonReader reader = new JsonReader(new InputStreamReader(inputStream)); )
{
reader.beginArray();
while (reader.hasNext())
{
Employee emp = new Gson().fromJson(reader, Employee.class);
System.out.println(emp.toString());
}
reader.endArray();
}
catch(Exception e)
{
e.printStackTrace();
}
}