user3470688 user3470688 - 1 year ago 75
Java Question

Reading in JSON files using Eclipse, do I need a library or not

I need to read a JSON file input from a file into my Java program.
I found some code that is reasonable to use which I have an example below.
But I am using Eclipse and I getting errors trying to reference JSONObject.
So apparently I do not have a library intalled in eclipse. So I was wondering what is the easiest way to get this to work. Do I need whole big library installed or is there another way without. If I do need to install a library which is the best/easiest and could you point to a link for download.


String jsonData = "";
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader(pathname));
while ((line = br.readLine()) != null) {
jsonData += line + "\n";
} catch (IOException e) {
} finally {
try {
if (br != null)
} catch (IOException ex) {
// System.out.println("File Content: \n" + jsonData);
JSONObject obj = new JSONObject(jsonData);

Answer Source

The class JSONObject is not part of the JDK so indeed you need to import a library to your project to be able to execute your code.

You can get it from here of if you use maven simply add the next dependency to the pom file of your project:


Finally please note that your code can be simplified by using a JSONTokener to be able parse a JSON content from an InputStream or a Reader which seems to be much more appropriate in your case, so your code should be:

JSONObject obj;
try (InputStream input = new FileInputStream(pathname)) {
    obj = new JSONObject(new JSONTokener(input));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download