1. import org.json.JSONObject;
  2. import org.json.JSONException;
  3. import java.util.logging.Logger;
  4. public class JsonHandler {
  5. private static final Logger logger = Logger.getLogger(JsonHandler.class.getName());
  6. public static JSONObject parseJson(String jsonString) {
  7. JSONObject jsonObject = null;
  8. try {
  9. jsonObject = new JSONObject(jsonString);
  10. logger.info("JSON parsing successful: " + jsonObject.toString(2)); // Log the parsed JSON (pretty printed)
  11. } catch (JSONException e) {
  12. logger.severe("JSON parsing failed: " + e.getMessage()); // Log the error message
  13. logger.severe("Original JSON string: " + jsonString); //Log the original string
  14. e.printStackTrace(); // Print the stack trace for detailed debugging
  15. }
  16. return jsonObject;
  17. }
  18. public static void main(String[] args) {
  19. String validJson = "{\"name\": \"John\", \"age\": 30}";
  20. String invalidJson = "{\"name\": \"John\", \"age\": 30"; //Missing closing bracket
  21. JSONObject validJsonObject = parseJson(validJson);
  22. if (validJsonObject != null) {
  23. System.out.println("Valid JSON Object: " + validJsonObject.toString());
  24. }
  25. JSONObject invalidJsonObject = parseJson(invalidJson);
  26. if(invalidJsonObject == null){
  27. System.out.println("Invalid JSON handled correctly.");
  28. }
  29. }
  30. }

Add your comment