1. import org.json.JSONObject;
  2. public class JsonValidator {
  3. /**
  4. * Validates a JSON response against a set of constraints.
  5. *
  6. * @param jsonResponse The JSON response to validate.
  7. * @param requiredFields A map of field names to expected data types (e.g., {"name": String, "age": Integer}).
  8. * @param allowedValues A map of field names to allowed values (e.g., {"status": ["active", "inactive"]}).
  9. * @return True if the JSON response meets all constraints, false otherwise.
  10. */
  11. public static boolean validateJson(JSONObject jsonResponse, java.util.Map<String, String> requiredFields, java.util.Map<String, Object[]> allowedValues) {
  12. if (jsonResponse == null) {
  13. System.err.println("JSON response is null.");
  14. return false;
  15. }
  16. // Check required fields
  17. for (Map.Entry<String, String> entry : requiredFields.entrySet()) {
  18. String fieldName = entry.getKey();
  19. String expectedType = entry.getValue();
  20. if (!jsonResponse.has(fieldName)) {
  21. System.err.println("Missing required field: " + fieldName);
  22. return false;
  23. }
  24. Object value = jsonResponse.get(fieldName);
  25. if (expectedType.equals("String") && !(value instanceof String)) {
  26. System.err.println("Field " + fieldName + " should be a String.");
  27. return false;
  28. } else if (expectedType.equals("Integer") && !(value instanceof Integer)) {
  29. System.err.println("Field " + fieldName + " should be an Integer.");
  30. return false;
  31. } else if (expectedType.equals("Double") && !(value instanceof Double)) {
  32. System.err.println("Field " + fieldName + " should be a Double.");
  33. return false;
  34. } else if (expectedType.equals("Boolean") && !(value instanceof Boolean)) {
  35. System.err.println("Field " + fieldName + " should be a Boolean.");
  36. return false;
  37. }
  38. }
  39. // Check allowed values
  40. for (Map.Entry<String, Object[]> entry : allowedValues.entrySet()) {
  41. String fieldName = entry.getKey();
  42. Object[] allowed = entry.getValue();
  43. if (jsonResponse.has(fieldName)) {
  44. Object value = jsonResponse.get(fieldName);
  45. boolean isValid = false;
  46. if (allowed != null) {
  47. for (Object allowedValue : allowed) {
  48. if (value.equals(allowedValue)) {
  49. isValid = true;
  50. break;
  51. }
  52. }
  53. }
  54. if (!isValid) {
  55. System.err.println("Field " + fieldName + " has an invalid value: " + value);
  56. return false;
  57. }
  58. }
  59. }
  60. return true; // All constraints met
  61. }
  62. public static void main(String[] args) {
  63. // Example usage
  64. JSONObject jsonResponse = new JSONObject();
  65. jsonResponse.put("name", "John Doe");
  66. jsonResponse.put("age", 30);
  67. jsonResponse.put("status", "active");
  68. java.util.Map<String, String> requiredFields = new java.util.HashMap<>();
  69. requiredFields.put("name", "String");
  70. requiredFields.put("age", "Integer");
  71. java.util.Map<String, Object[]> allowedValues = new java.util.HashMap<>();
  72. Object[] allowedStatuses = {"active", "inactive"};
  73. allowedValues.put("status", allowedStatuses);
  74. boolean isValid = validateJson(jsonResponse, requiredFields, allowedValues);
  75. System.out.println("JSON is valid: " + isValid);
  76. //Example of invalid JSON
  77. JSONObject invalidJson = new JSONObject();
  78. invalidJson.put("name", 123);
  79. invalidJson.put("age", "abc");
  80. isValid = validateJson(invalidJson, requiredFields, allowedValues);
  81. System.out.println("Invalid JSON is valid: " + isValid);
  82. }
  83. }

Add your comment