import org.json.JSONObject;
import org.json.JSONException;
import java.util.logging.Logger;
public class JsonHandler {
private static final Logger logger = Logger.getLogger(JsonHandler.class.getName());
public static JSONObject parseJson(String jsonString) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(jsonString);
logger.info("JSON parsing successful: " + jsonObject.toString(2)); // Log the parsed JSON (pretty printed)
} catch (JSONException e) {
logger.severe("JSON parsing failed: " + e.getMessage()); // Log the error message
logger.severe("Original JSON string: " + jsonString); //Log the original string
e.printStackTrace(); // Print the stack trace for detailed debugging
}
return jsonObject;
}
public static void main(String[] args) {
String validJson = "{\"name\": \"John\", \"age\": 30}";
String invalidJson = "{\"name\": \"John\", \"age\": 30"; //Missing closing bracket
JSONObject validJsonObject = parseJson(validJson);
if (validJsonObject != null) {
System.out.println("Valid JSON Object: " + validJsonObject.toString());
}
JSONObject invalidJsonObject = parseJson(invalidJson);
if(invalidJsonObject == null){
System.out.println("Invalid JSON handled correctly.");
}
}
}
Add your comment