Creación de una Utilidad JSON Reutilizable
En el desarrollo de software, es una buena práctica escribir código reutilizable. En lugar de repetir la lógica de lectura de archivos en cada clase que la necesite, podemos crear una clase de utilidad. Este enfoque, conocido como "Don't Repeat Yourself" (DRY - No te repitas), hace que tu código sea más limpio, más fácil de mantener y menos propenso a errores.
Creación de la Clase JsonUtils
Creemos una clase de utilidad para encapsular la lógica de lectura de un archivo JSON.
- En WebIDE, cree un nuevo archivo llamado
JsonUtils.java dentro del directorio src/main/java/com/labex.
- Agregue el siguiente código:
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);
}
}
Esta clase contiene un único método static, readJsonObjectFromFile. Un método static pertenece a la clase en sí misma en lugar de a una instancia, por lo que puedes llamarlo directamente usando el nombre de la clase (por ejemplo, JsonUtils.readJsonObjectFromFile(...)) sin crear un objeto.
Uso de la Clase de Utilidad
Ahora, creemos una clase de aplicación principal que utilice nuestra nueva utilidad.
- En WebIDE, cree un nuevo archivo llamado
Main.java dentro del directorio src/main/java/com/labex.
- Agregue el siguiente código a
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());
}
}
}
Esta clase Main es mucho más limpia. Delega la tarea de leer y analizar el archivo a JsonUtils, centrándose únicamente en qué hacer con el JSONObject resultante.
Ejecución de la Aplicación Principal
Finalmente, ejecutemos nuestra clase Main.
- Abra la terminal en WebIDE.
- Ejecute el siguiente comando:
mvn compile exec:java -Dexec.mainClass="com.labex.Main"
Verá la siguiente salida:
--- Data read using JsonUtils ---
Name: John Doe
City: Anytown
Successfully read JSON using JsonUtils.
Al crear una clase de utilidad, ha hecho que su código sea más modular y reutilizable, lo cual es un principio clave de la ingeniería de software efectiva.