141

I want to read this JSON file with java using json simple library.

My JSON file looks like this:

[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw"
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata"
        ],
        "job":"Doctor"
    }
]

This is the java code I wrote to read this file:

package javaapplication1;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class JavaApplication1 {
    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {     
            Object obj = parser.parse(new FileReader("c:\\file.json"));

            JSONObject jsonObject =  (JSONObject) obj;

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String city = (String) jsonObject.get("city");
            System.out.println(city);

            String job = (String) jsonObject.get("job");
            System.out.println(job);

            // loop array
            JSONArray cars = (JSONArray) jsonObject.get("cars");
            Iterator<String> iterator = cars.iterator();
            while (iterator.hasNext()) {
             System.out.println(iterator.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

But I get the following exception:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)

Can somebody tell me what I am doing wrong? The whole file is a array and there are objects and another array (cars) in the whole array of the file. But i dont know how I can parse the whole array into a java array. I hope somebody can help me with a code line which I am missing in my code.

Thanks

OO7
  • 2,785
  • 1
  • 21
  • 33
billz
  • 1,419
  • 3
  • 11
  • 7
  • Please refer the below answer https://stackoverflow.com/questions/7463414/what-s-the-best-way-to-load-a-jsonobject-from-a-json-text-file – Muhammed Fasil Sep 28 '22 at 06:59
  • don't want to use data model? it's as easy as a pie, if you use gson you can simply parse it by s.th like this: `List info = new Gson().fromJson(YOUR_JSON_STRING, new TypeToken>() {}.getType())` – Mostafa Nazari Dec 15 '22 at 06:46

22 Answers22

107

The whole file is an array and there are objects and other arrays (e.g. cars) in the whole array of the file.

As you say, the outermost layer of your JSON blob is an array. Therefore, your parser will return a JSONArray. You can then get JSONObjects from the array ...

  JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)
  {
    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");
    System.out.println(name);

    String city = (String) person.get("city");
    System.out.println(city);

    String job = (String) person.get("job");
    System.out.println(job);

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)
    {
      System.out.println(c+"");
    }
  }

For reference, see "Example 1" on the json-simple decoding example page.

Binyamin Regev
  • 914
  • 5
  • 19
  • 31
Greg Kopff
  • 15,945
  • 12
  • 55
  • 78
  • Thanks. It reads the first object course, instructor, students array and title object. How can I read the next ones too? – billz Jun 07 '12 at 07:08
  • Well, you want to process all of the items in the array in a loop. My code just gets you the first item (`a.get(0)`) because that was the closest match to your original code. The json-simple documentation says a `JSONArray` is `java.util.List`, so you can iterate over the elements just like you would a normal list. Is that enough to go on? – Greg Kopff Jun 07 '12 at 08:06
  • I have tried that but it did not work. Can you give me a code example – billz Jun 07 '12 at 08:22
  • @billz: I don't have the library to be able to execute and test this -- but I've edited the answer with my guess. – Greg Kopff Jun 07 '12 at 08:55
  • 4
    This works great ! Please note: use the import as is in this example (i.e. with 'simple'), otherwise it will not allow 'for each'. Wrong: import org.json.JSONArray; import org.json.JSONObject; Correct: import org.json.simple.JSONArray; import org.json.simple.JSONObject; – Krishna Sapkota Jul 31 '14 at 16:14
  • Unexpected token LEFT BRACE({) at position 156. – Spartan Jan 30 '16 at 14:45
  • It's giving me error as :- Can only iterate over an array or an instance of java.lang.Iterable on line for (Object o : a) – Shubham Jain Mar 18 '16 at 11:39
  • @ShubhamJain: which JSON library are you using? The one in the answer is one where a `JSONArray` is an `Iterable` - looks like yours does not. Here's the source of the [class in this answer](https://github.com/fangyidong/json-simple/blob/master/src/main/java/org/json/simple/JSONArray.java). – Greg Kopff Mar 19 '16 at 01:50
  • very creative variable names – Tilak Madichetti Jun 03 '16 at 11:58
  • 1
    how to give the FileReader a relative path, may be from /resources folder – prime Aug 15 '17 at 16:53
  • 4
    `parser` from which library (import) is it? – user25 Jan 26 '19 at 21:34
  • 1
    ` JSONParser parser=new JSONParser();` – Infinity Jul 04 '22 at 10:48
81

You can use jackson library and simply use these 3 lines to convert your json file to Java Object.

ObjectMapper mapper = new ObjectMapper();
InputStream is = Test.class.getResourceAsStream("/test.json");
testObj = mapper.readValue(is, Test.class);
Mady
  • 5,016
  • 7
  • 35
  • 46
23

Add Jackson databind:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.0.pr2</version>
</dependency>

Create DTO class with related fields and read JSON file:

ObjectMapper objectMapper = new ObjectMapper();
ExampleClass example = objectMapper.readValue(new File("example.json"), ExampleClass.class);
Justinas Jakavonis
  • 8,220
  • 10
  • 69
  • 114
15

Reading from JsonFile

public static ArrayList<Employee> readFromJsonFile(String fileName){
        ArrayList<Employee> result = new ArrayList<Employee>();

        try{
            String text = new String(Files.readAllBytes(Paths.get(fileName)), StandardCharsets.UTF_8);

            JSONObject obj = new JSONObject(text);
            JSONArray arr = obj.getJSONArray("employees");

            for(int i = 0; i < arr.length(); i++){
                String name = arr.getJSONObject(i).getString("name");
                short salary = Short.parseShort(arr.getJSONObject(i).getString("salary"));
                String position = arr.getJSONObject(i).getString("position");
                byte years_in_company = Byte.parseByte(arr.getJSONObject(i).getString("years_in_company")); 
                if (position.compareToIgnoreCase("manager") == 0){
                    result.add(new Manager(name, salary, position, years_in_company));
                }
                else{
                    result.add(new OrdinaryEmployee(name, salary, position, years_in_company));
                }
            }           
        }
        catch(Exception ex){
            System.out.println(ex.toString());
        }
        return result;
    }
thor
  • 21,418
  • 31
  • 87
  • 173
Teddy
  • 151
  • 1
  • 2
9

Use google-simple library.

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

Please find the sample code below:

public static void main(String[] args) {
    try {
        JSONParser parser = new JSONParser();
        //Use JSONObject for simple JSON and JSONArray for array of JSON.
        JSONObject data = (JSONObject) parser.parse(
              new FileReader("/resources/config.json"));//path to the JSON file.

        String json = data.toJSONString();
    } catch (IOException | ParseException e) {
        e.printStackTrace();
    }
}

Use JSONObject for simple JSON like {"id":"1","name":"ankur"} and JSONArray for array of JSON like [{"id":"1","name":"ankur"},{"id":"2","name":"mahajan"}].

Ankur Mahajan
  • 3,396
  • 3
  • 31
  • 42
7

Might be of help for someone else facing the same issue.You can load the file as string and then can convert the string to jsonobject to access the values.

import java.util.Scanner;
import org.json.JSONObject;
String myJson = new Scanner(new File(filename)).useDelimiter("\\Z").next();
JSONObject myJsonobject = new JSONObject(myJson);
Srijan Sharma
  • 683
  • 1
  • 9
  • 19
5

Gson can be used here:

public Object getObjectFromJsonFile(String jsonData, Class classObject) {
    Gson gson = new Gson();
    JsonParser parser = new JsonParser();
    JsonObject object = (JsonObject) parser.parse(jsonData);
    return gson.fromJson(object, classObject);
}
Aman Garg
  • 131
  • 2
  • 2
4
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class Delete_01 {
    public static void main(String[] args) throws FileNotFoundException,
            IOException, ParseException {

        JSONParser parser = new JSONParser();
        JSONArray jsonArray = (JSONArray) parser.parse(new FileReader(
                "delete_01.json"));

        for (Object o : jsonArray) {
            JSONObject person = (JSONObject) o;

            String strName = (String) person.get("name");
            System.out.println("Name::::" + strName);

            String strCity = (String) person.get("city");
            System.out.println("City::::" + strCity);

            JSONArray arrays = (JSONArray) person.get("cars");
            for (Object object : arrays) {
                System.out.println("cars::::" + object);
            }
            String strJob = (String) person.get("job");
            System.out.println("Job::::" + strJob);
            System.out.println();

        }

    }
}
Delvin
  • 41
  • 1
2

Following is the working solution to your problem statement as,

File file = new File("json-file.json");
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(file));
    JSONArray jsonArray = new JSONArray(obj.toString());
    for (int i = 0; i < jsonArray.length(); i++) {
      JSONObject jsonObject = jsonArray.getJSONObject(i);
      System.out.println(jsonObject.get("name"));
      System.out.println(jsonObject.get("city"));
      System.out.println(jsonObject.get("job"));
      jsonObject.getJSONArray("cars").forEach(System.out::println);
    }
1

Hope this example helps too

I have done java coding in a similar way for the below json array example as follows :

following is the json data format : stored as "EMPJSONDATA.json"

[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},

{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]

public class Jsonminiproject {

public static void main(String[] args) {

      JSONParser parser = new JSONParser();

    try {
        JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
        for (Object o : a)
        {
            JSONObject employee = (JSONObject) o;

            Long no = (Long) employee.get("EMPNO");
            System.out.println("Employee Number : " + no);

            String st = (String) employee.get("EMP_NAME");
            System.out.println("Employee Name : " + st);

            String dob = (String) employee.get("DOB");
            System.out.println("Employee DOB : " + dob);

            String doj = (String) employee.get("DOJ");
            System.out.println("Employee DOJ : " + doj);

            String role = (String) employee.get("ROLE");
            System.out.println("Employee Role : " + role);

            System.out.println("\n");

        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

}
1
package com.json;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

public class ReadJSONFile {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {
            Object obj = parser.parse(new FileReader("C:/My Workspace/JSON Test/file.json"));

            JSONArray array = (JSONArray) obj;
            JSONObject jsonObject = (JSONObject) array.get(0);

            String name = (String) jsonObject.get("name");
            System.out.println(name);

            String city = (String) jsonObject.get("city");
            System.out.println(city);

            String job = (String) jsonObject.get("job");
            System.out.println(job);

            // loop array
            JSONArray cars = (JSONArray) jsonObject.get("cars");
            Iterator<String> iterator = cars.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

}
P RAJESH
  • 23
  • 3
1

This issue occurs when you are importing the org. json library for JSONObject class. Instead you need to import org.json.simple library.

1
private static final JsonParser JSON_PARSER = new JsonParser();    
private static final String FILE_PATH = "configuration/data.json";

private JsonObject readJsonDataFromFile() {
    try {
        File indexFile = new File(FILE_PATH);
        String fileData = Files.toString(indexFile, Charsets.UTF_8);
        return (JsonObject) JSON_PARSER.parse(fileData);
    } catch (IOException | JsonParseException e) {
        String error = String.format("Error while reading file %s", FILE_PATH);
        log.error(error);
        throw new RuntimeException(error, e);
    }
}
HIMANSHU GOYAL
  • 471
  • 2
  • 11
1
public class JsonParser {

    public static JSONObject parse(String file) {
        InputStream is = JsonParser.class.getClassLoader().getResourceAsStream(file);
        assert is != null;
        return new JSONObject(new JSONTokener(is));
    }
}
// Read Json 
    JSONObject deviceObj = new JSONObject(JsonParser.parse("Your Json filename").getJSONObject(deviceID).toString());

Perform logic to iterate

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
1
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class JsonParserTest {
    public static void main(String[] args) throws IOException {
        String data = new String(Files.readAllBytes(Paths.get("C:/json.txt"))); 
        JsonElement jsonElement = JsonParser.parseString(data);
        JsonObject json = jsonElement.getAsJsonObject();
        System.out.println(json.get("userId"));
        System.out.println(json.get("id"));
        System.out.println(json.get("title"));
        System.out.println(json.get("completed"));
    }
}

Use the below repositay from GSON.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.6</version>
</dependency>
Sergey
  • 3,253
  • 2
  • 33
  • 55
  • 1
    bravo! `gson` is good choice, but, add sample of `JsonArray` as this question requested. in your code you can add `System.out.println(StreamSupport.stream(json.getAsJsonArray("cars").spliterator(), false).map(i -> i.getAsString()).collect(Collectors.toList());` or any equivalent phrase – Mostafa Nazari Dec 15 '22 at 06:32
  • and also, pay attention to the json, the root is an array of objects. good luck – Mostafa Nazari Dec 15 '22 at 06:40
0

Sample Json

{
    "per_page": 3,
    "total": 12,
    "data": [{
            "last_name": "Bluth",
            "id": 1,
            "avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg",
            "first_name": "George"
        },
        {
            "last_name": "Weaver",
            "id": 2,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/josephstein/128.jpg",
            "first_name": "Janet"
        },
        {
            "last_name": "Wong",
            "id": 3,
            //"avatar": "https://s3.amazonaws.com/uifaces/faces/twitter/olegpogodaev/128.jpg",
            "first_name": "Emma"
        }
    ],
    "page": 1,
    "total_pages": 4
}

First If statement will convert the single data from the body Second if statement will differentiate the JsonArray object

public static String getvalueJpath(JSONObject responseJson, String Jpath ) {
        Object obj = responseJson;
        for(String s : Jpath.split("/"))
            if (s.isEmpty())
                if(!(s.contains("[") || s.contains("]")))
                    obj = ((JSONObject) obj).get(s);
                else
                    if(s.contains("[") || s.contains("]"))
                        obj = ((JSONArray)((JSONObject)obj).get(s.split("\\[")[0])).get(Integer.parseInt(s.split("//[")[1].replaceAll("]", "")));

        return obj.toString();
    }
}
Gahan
  • 4,075
  • 4
  • 24
  • 44
0

Solution using Jackson library. Sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]
Atul KS
  • 908
  • 11
  • 21
0

your json file look like this

enter image description here

import java.io.*;
import java.util.*;
import org.json.simple.*;
import org.json.simple.parser.*;
public class JSONReadFromTheFileTest {
   public static void main(String[] args) {
      JSONParser parser = new JSONParser();
      try {
         Object obj = parser.parse(new FileReader("/Users/User/Desktop/course.json"));
         JSONObject jsonObject = (JSONObject)obj;
         String name = (String)jsonObject.get("Name");
         String course = (String)jsonObject.get("Course");
         JSONArray subjects = (JSONArray)jsonObject.get("Subjects");
         System.out.println("Name: " + name);
         System.out.println("Course: " + course);
         System.out.println("Subjects:");
         Iterator iterator = subjects.iterator();
         while (iterator.hasNext()) {
            System.out.println(iterator.next());
         }
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

the output is

Name: Raja
Course: MCA
Subjects:
subject1: MIS
subject2: DBMS
subject3: UML

took it from here

Vladi
  • 1,662
  • 19
  • 30
0
  try {
      Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));

     // JSONArray array = (JSONArray) obj;
      JSONObject jsonObject = (JSONObject) obj;
      
      JSONObject orchestration = (JSONObject) jsonObject.get("orchestration");
     

      JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
     

      JSONObject schedule = (JSONObject) trigger.get("schedule");
    
       JSONObject trade = (JSONObject) schedule.get("trade-query");
    
     // loop array
      JSONArray filter = (JSONArray) trade.get("filter");
   
  
      for (Object o : filter) {
          JSONObject person = (JSONObject) o;

          String strName = (String) person.get("name");
          System.out.println("Name::::" + strName);

          String operand = (String) person.get("operand");
          System.out.println("City::::" + operand);

          String value = (String) person.get("value");
          System.out.println("value::::" + value);
      }
     
      JSONArray parameter = (JSONArray) trade.get("parameter");
      for (Object o : parameter) {
          JSONObject person = (JSONObject) o;

          String strName = (String) person.get("name");
          System.out.println("Name::::" + strName);

          String value = (String) person.get("value");
          System.out.println("value::::" + value);
      }


  } catch (FileNotFoundException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  } catch (ParseException e) {
      e.printStackTrace();
  }

}

0
  try {
      //Object obj = parser.parse(new FileReader("C:/Local Disk/file.json"));
      
       // create object mapper instance
        ObjectMapper mapper = new ObjectMapper();

        // convert JSON string to Book object
        Object obj = mapper.readValue(Paths.get("C:/Local Disk/file.json").toFile(), Object.class);

        // print book
        System.out.println(obj);

        String jsonInString = new Gson().toJson(obj);
        JSONObject mJSONObject = new JSONObject(jsonInString);
        
        System.out.println("value::::" + mJSONObject);  
      
      JSONObject orchestration = (JSONObject) mJSONObject.get("orchestration");
     

      JSONObject trigger = (JSONObject) orchestration.get("trigger-definition");
     

      JSONObject schedule = (JSONObject) trigger.get("schedule");
    
       JSONObject trade = (JSONObject) schedule.get("trade-query");
    
     // loop array
      JSONArray filter = (JSONArray) trade.get("filter");
   
  
      for (Object o : filter) {
          JSONObject person = (JSONObject) o;

          String strName = (String) person.get("name");
          System.out.println("Name::::" + strName);

          String operand = (String) person.get("operand");
          System.out.println("City::::" + operand);

          String value = (String) person.get("value");
          System.out.println("value::::" + value);
      }
     
      JSONArray parameter = (JSONArray) trade.get("parameter");
      for (Object o : parameter) {
          JSONObject person = (JSONObject) o;

          String strName = (String) person.get("name");
          System.out.println("Name::::" + strName);

          String value = (String) person.get("value");
          System.out.println("value::::" + value);
      }


  } catch (FileNotFoundException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  }
  
  

  
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 05 '22 at 16:45
0

Add Jackson dependency to use ObjectMapper in your pom.xml file.

 <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.12.3</version>
 </dependency>

In your main class App.java, use the mapper to convert your JSON file to JsonNode

public static void main(Strings[] args) {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode json = mapper.readValue(new File("/path/to/file"), JsonNode.class);
    json.fields()
            .forEachRemaining((field) -> {
                String key = field.getKey();
                JsonNode value = field.getValue(); // value can be yet another JSON
               // Do your stuff with the keys and values here.
            });


}
-4

You can use readAllBytes.

return String(Files.readAllBytes(Paths.get(filePath)),StandardCharsets.UTF_8);