import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JsonValidator {
public static void validateJson(String jsonString) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
// Define default values for expected fields
Map<String, Object> defaults = new HashMap<>();
defaults.put("name", "Unknown");
defaults.put("age", 0);
defaults.put("city", "DefaultCity");
defaults.put("isActive", false);
// Validate required fields
if (jsonObject.has("name") && jsonObject.get("name") == null) {
System.err.println("Error: 'name' field is missing.");
jsonObject.put("name", defaults.get("name"));
} else if (jsonObject.has("name") && ((String) jsonObject.get("name")).isEmpty()) {
System.err.println("Error: 'name' field is empty.");
jsonObject.put("name", defaults.get("name"));
}
if (jsonObject.has("age") && jsonObject.get("age") == null) {
System.err.println("Error: 'age' field is missing.");
jsonObject.put("age", defaults.get("age"));
} else if (jsonObject.has("age") && !jsonObject.get("age").isNumeric()) {
System.err.println("Error: 'age' field is not a number.");
jsonObject.put("age", defaults.get("age"));
}
if (jsonObject.has("city") && jsonObject.get("city") == null) {
System.err.println("Error: 'city' field is missing.");
jsonObject.put("city", defaults.get("city"));
}
if (jsonObject.has("isActive") && jsonObject.get("isActive") == null) {
System.err.println("Error: 'isActive' field is missing.");
jsonObject.put("isActive", defaults.get("isActive"));
} else if (jsonObject.has("isActive") && !jsonObject.get("isActive").isBoolean()) {
System.err.println("Error: 'isActive' field is not a boolean.");
jsonObject.put("isActive", defaults.get("isActive"));
}
// Print the validated JSON (optional)
System.out.println("Validated JSON: " + jsonObject.toString(2));
} catch (Exception e) {
System.err.println("Error parsing JSON: " + e.getMessage());
System.err.println("Stacktrace: " + e.printStackTrace());
}
}
public static void main(String[] args) {
// Example usage
String json1 = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\", \"isActive\": true}";
String json2 = "{\"age\": 25, \"city\": \"London\"}";
String json3 = "{\"name\": null, \"age\": \"abc\"}";
String json4 = "{\"name\": \"\", \"age\": 25}";
String json5 = "{\"name\": \"Jane\", \"age\": 28, \"city\": null, \"isActive\": \"yes\"}";
System.out.println("Validating JSON 1:");
validateJson(json1);
System.out.println();
System.out.println("Validating JSON 2:");
validateJson(json2);
System.out.println();
System.out.println("Validating JSON 3:");
validateJson(json3);
System.out.println();
System.out.println("Validating JSON 4:");
validateJson(json4);
System.out.println();
System.out.println("Validating JSON 5:");
validateJson(json5);
System.out.println();
}
}
Add your comment