Creating a Reusable JSON Utility
In software development, it is a best practice to write reusable code. Instead of repeating the file-reading logic in every class that needs it, we can create a utility class. This approach, known as "Don't Repeat Yourself" (DRY), makes your code cleaner, more maintainable, and less prone to errors.
Creating the JsonUtils
Class
Let's create a utility class to encapsulate the logic for reading a JSON file.
- In the WebIDE, create a new file named
JsonUtils.java
inside the src/main/java/com/labex
directory.
- Add the following code:
package com.labex;
import org.json.JSONObject;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class JsonUtils {
/**
* Reads a JSON file from a relative path and parses it into a JSONObject.
*
* @param filePath The relative path to the JSON file.
* @return A JSONObject representing the file's content.
* @throws IOException if an I/O error occurs reading from the file.
*/
public static JSONObject readJsonObjectFromFile(String filePath) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(filePath)));
return new JSONObject(content);
}
}
This class contains a single static
method, readJsonObjectFromFile
. A static
method belongs to the class itself rather than an instance, so you can call it directly using the class name (e.g., JsonUtils.readJsonObjectFromFile(...)
) without creating an object.
Using the Utility Class
Now, let's create a main application class that uses our new utility.
- In the WebIDE, create a new file named
Main.java
inside the src/main/java/com/labex
directory.
- Add the following code to
Main.java
:
package com.labex;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
try {
// Use the utility class to read the JSON file
JSONObject data = JsonUtils.readJsonObjectFromFile("src/main/resources/data.json");
// Now we can work with the JSONObject as before
String name = data.getString("name");
String city = data.getJSONObject("address").getString("city");
System.out.println("--- Data read using JsonUtils ---");
System.out.println("Name: " + name);
System.out.println("City: " + city);
System.out.println("\nSuccessfully read JSON using JsonUtils.");
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
This Main
class is much cleaner. It delegates the task of reading and parsing the file to JsonUtils
, focusing only on what to do with the resulting JSONObject
.
Running the Main Application
Finally, let's run our Main
class.
- Open the terminal in the WebIDE.
- Execute the following command:
mvn compile exec:java -Dexec.mainClass="com.labex.Main"
You will see the following output:
--- Data read using JsonUtils ---
Name: John Doe
City: Anytown
Successfully read JSON using JsonUtils.
By creating a utility class, you have made your code more modular and reusable, which is a key principle of effective software engineering.