1. import org.json.JSONObject;
  2. import org.json.JSONException;
  3. public class JsonSuppressor {
  4. public static JSONObject parseJsonWithSuppression(String jsonString) {
  5. JSONObject jsonObject = null;
  6. try {
  7. jsonObject = new JSONObject(jsonString); // Attempt to parse
  8. } catch (JSONException e) {
  9. // Suppress the exception and proceed with manual override
  10. System.err.println("JSON parsing error: " + e.getMessage());
  11. //Manual override - Example: set default values or fix specific errors
  12. if(jsonString != null && !jsonString.isEmpty()) {
  13. try {
  14. jsonObject = new JSONObject(jsonString.replace("missing_key", "default_value"));
  15. } catch (JSONException overrideEx) {
  16. System.err.println("Override error: " + overrideEx.getMessage());
  17. jsonObject = new JSONObject(); //Create empty object if override fails.
  18. }
  19. } else {
  20. jsonObject = new JSONObject(); //Create empty object if jsonString is null/empty
  21. }
  22. }
  23. return jsonObject;
  24. }
  25. public static void main(String[] args) {
  26. String jsonStringWithErrors = "{ \"name\": \"John\", \"age\": 30, missing_key: \"default_value\" }";
  27. JSONObject parsedJson = parseJsonWithSuppression(jsonStringWithErrors);
  28. if (parsedJson != null) {
  29. System.out.println(parsedJson.toString(2)); // Print the parsed JSON
  30. }
  31. String emptyJson = null;
  32. JSONObject parsedEmptyJson = parseJsonWithSuppression(emptyJson);
  33. if(parsedEmptyJson != null){
  34. System.out.println("Empty JSON parsed successfully");
  35. }
  36. String invalidJson = "{invalid json}";
  37. JSONObject parsedInvalidJson = parseJsonWithSuppression(invalidJson);
  38. if(parsedInvalidJson != null){
  39. System.out.println("Invalid JSON parsed successfully");
  40. }
  41. }
  42. }

Add your comment