1. import org.json.JSONObject;
  2. import org.json.JSONException;
  3. public class JsonValidator {
  4. public static void validateJson(String jsonString) {
  5. try {
  6. // Attempt to parse the JSON string
  7. JSONObject jsonObject = new JSONObject(jsonString);
  8. // If parsing is successful, print a success message.
  9. System.out.println("JSON is valid.");
  10. } catch (JSONException e) {
  11. // If parsing fails, print the error message.
  12. System.err.println("JSON Error: " + e.getMessage());
  13. //Optional: print stacktrace for debugging
  14. //e.printStackTrace();
  15. }
  16. }
  17. public static void main(String[] args) {
  18. //Example usage
  19. String validJson = "{ \"name\": \"John\", \"age\": 30 }";
  20. String invalidJson = "{ \"name\": \"John\", \"age\": }";
  21. System.out.println("Valid JSON Validation:");
  22. validateJson(validJson);
  23. System.out.println("\nInvalid JSON Validation:");
  24. validateJson(invalidJson);
  25. }
  26. }

Add your comment