Explain Codes LogoExplain Codes Logo

How to read a JSON file into Java with the Simple JSON library

java
json-parsing
file-handling
error-handling
Anton ShumikhinbyAnton Shumikhin·Feb 20, 2025
TLDR

Here is a quick solution for those who are in a hurry. This is a way to load and parse a JSON file in Java employing the Simple JSON library:

import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; JSONParser parser = new JSONParser(); try { JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("yourfile.json")); String data = (String) jsonObject.get("yourKey"); // Honey, I found the key! } catch (Exception e) { e.printStackTrace(); // Always good to know WHY stuff broke... }

Replace "yourfile.json" with the path to your JSON file and "yourKey" with the specific data key that you are interested in.

Parsing Arrays: It's not as scary as it sounds!

JSONArray: Get on the train

Perhaps your JSON file contains an array. To deal with this situation, use the JSONArray object and loop through the array to extract information from each object.

import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; JSONParser parser = new JSONParser(); try { JSONArray array = (JSONArray) parser.parse(new FileReader("yourfile.json")); for (Object item : array) { JSONObject jsonObject = (JSONObject) item; // Do whatever you want here... sky's the limit! Or maybe your creativity is, but who's judging? } } catch (Exception e) { e.printStackTrace(); // Ahh, the bitter taste of failure... }

Java Object Deja Vu

To really make the most of your parsed JSON data, it's pretty handy to store the data in Java objects. Why you may ask? Because it helps to visualize and manage the data effectively.

public class MyDataModel { private String key; // Private but accessible, classic... // Other fields... // Getters and setters... }

Using an ObjectMapper or similar tools, you could map the JSON data to instances of MyDataModel.

Robust file handling: because who doesn't love files?

Nothing’s worse than having a program crash on the production server! So for smooth operations, use getResourceAsStream(). This is particularly useful while working with files in a resource directory.

InputStream in = getClass().getResourceAsStream("/path/to/yourfile.json"); JSONParser parser = new JSONParser(); try { JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader(in));// Read, Parse, Store, Repeat... //... } catch (Exception e) { e.printStackTrace(); }

Also, don't forget to use try-catch blocks. This will handle any IOException or ParseException, making your application crash-proof (well, it's a step in the right direction anyway).

Deep Dive: The JSON parsing rabbit hole

Nested JSON elements: like a box within a box...within a box

Contending with nested JSON objects? Remember to cast your parsed JSON responsibly. This will keep ClassCastException at bay.

JSONParser parser = new JSONParser(); try { JSONObject root = (JSONObject) parser.parse(new FileReader("nested.json")); //Inception of JSON files JSONArray items = (JSONArray) root.get("items"); for (Object item : items) { JSONObject jsonObject = (JSONObject) item; JSONArray details = (JSONArray) jsonObject.get("details"); for (Object detail : details) { System.out.println(detail); //Here's Johnny!... I mean, the detail! } } } catch (Exception e) { e.printStackTrace(); //Errorception }

Read all the bytes: even the ones hiding in the corner

If you choose to read all bytes from a file before parsing, Files.readAllBytes and Paths.get are your best friends:

Path path = Paths.get("yourfile.json"); try { String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); JSONObject jsonObject = (JSONObject) new JSONParser().parse(content);// Enjoy the content, because why not? //... } catch (IOException | ParseException e) { e.printStackTrace();// Oh, look! An exception... }

JSON and Java ArrayLists: A match made in Heaven

Is there anything more flexible and easy to access than a good-old ArrayList? Doubt it!

ArrayList<MyDataModel> dataList = new ArrayList<>(); for (Object item : jsonArray) { JSONObject jsonObject = (JSONObject) item; MyDataModel data = new MyDataModel(); data.setKey((String) jsonObject.get("key")); // Set other properties... dataList.add(data);// Welcome to the list, buddy! }

No more boo-boos with try-catch

Ensure sleek error handling by catching IOException and ParseException separately. This leads to better messaging and graceful recovery:

try { JSONObject jsonObject = (JSONObject) new JSONParser().parse(new FileReader("yourfile.json")); //... } catch (IOException e) { System.err.println("Can't read the file... Maybe it went on a vacation?");// Error message you can frame and hang on your wall } catch (ParseException e) { System.err.println("Error parsing the JSON. JSON, why you no co-operate?");// Error message straight out of a sci-fi movie }