JSON Validation - potatoscript/json GitHub Wiki
Welcome to JSON Validation in Java â where we ensure that your JSON data is structured perfectly and error-free! đđĩī¸ââī¸
JSON Validation is the process of verifying that a JSON document:
- â Follows correct syntax.
- â Contains valid data types.
- â Adheres to a defined schema (optional but recommended for complex data structures).
JSON data exchanged between systems can sometimes be:
- â Malformed (missing brackets, commas).
- â Containing unexpected or invalid values.
- â Missing required keys.
-
{"name": "Lucy", "age": 26, }
âĄī¸ â Trailing comma. -
{"name": "Lucy", "age": "twenty-six"}
âĄī¸ â Incorrect data type.
There are multiple ways to validate JSON in Java:
You can validate basic JSON syntax using ObjectMapper
from the Jackson library.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonValidationExample {
public static void main(String[] args) {
String json = "{\"name\":\"Lucy Berry\",\"age\":26}";
ObjectMapper mapper = new ObjectMapper();
try {
// Basic validation: Parse JSON to check syntax
mapper.readTree(json);
System.out.println("â
JSON is valid!");
} catch (Exception e) {
System.out.println("â Invalid JSON: " + e.getMessage());
}
}
}
â Explanation:
-
readTree()
parses the JSON. - If the JSON is invalid, an exception is thrown.
To ensure JSON follows a defined schema, use the everit-org/json-schema library.
<dependency>
<groupId>org.everit.json</groupId>
<artifactId>org.everit.json.schema</artifactId>
<version>1.14.3</version>
</dependency>
What is a JSON Schema?
- đ Defines the structure, data types, and constraints of a JSON document.
- â Ensures that the JSON follows a predefined format.
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "age"]
}
Save the schema in user_schema.json
:
{
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "integer" },
"email": { "type": "string", "format": "email" }
},
"required": ["name", "age"]
}
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.FileInputStream;
public class JsonSchemaValidationExample {
public static void main(String[] args) {
try {
// Load JSON Schema
FileInputStream schemaStream = new FileInputStream("user_schema.json");
JSONObject jsonSchema = new JSONObject(new JSONTokener(schemaStream));
// Load JSON Data
String jsonData = """
{
"name": "Lucy Berry",
"age": 26,
"email": "[email protected]"
}
""";
JSONObject jsonObject = new JSONObject(jsonData);
// Validate JSON
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonObject);
System.out.println("â
JSON is valid against the schema!");
} catch (Exception e) {
System.out.println("â JSON validation failed: " + e.getMessage());
}
}
}
â Explanation:
-
SchemaLoader.load()
loads the schema from the file. -
schema.validate()
checks JSON against the schema.
If you prefer to use annotations to validate JSON properties, you can annotate Java classes.
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.validation.constraints.*;
class User {
@JsonProperty("name")
@NotNull(message = "Name is required")
private String name;
@JsonProperty("age")
@Min(value = 18, message = "Age must be 18 or above")
private int age;
@JsonProperty("email")
@Email(message = "Invalid email format")
private String email;
// Getters and Setters
public String getName() { return name; }
public int getAge() { return age; }
public String getEmail() { return email; }
}
public class AnnotationValidationExample {
public static void main(String[] args) {
String json = """
{
"name": "Lucy Berry",
"age": 16,
"email": "lucy.berry@invalid"
}
""";
ObjectMapper mapper = new ObjectMapper();
try {
User user = mapper.readValue(json, User.class);
System.out.println("â
Valid JSON!");
} catch (Exception e) {
System.out.println("â JSON validation failed: " + e.getMessage());
}
}
}
â Explanation:
- Use
@NotNull
,@Min
, and@Email
to validate fields. - Invalid data triggers validation errors.
When dealing with nested JSON, make sure the structure is properly validated.
import com.fasterxml.jackson.databind.ObjectMapper;
import org.everit.json.schema.Schema;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.FileInputStream;
public class NestedJsonValidationExample {
public static void main(String[] args) {
try {
// Load Nested JSON Schema
FileInputStream schemaStream = new FileInputStream("nested_schema.json");
JSONObject jsonSchema = new JSONObject(new JSONTokener(schemaStream));
// Load Nested JSON Data
String nestedJsonData = """
{
"user": {
"name": "Lucy Berry",
"age": 26,
"address": {
"city": "Fukuoka",
"postal_code": "810-0011"
}
}
}
""";
JSONObject jsonObject = new JSONObject(nestedJsonData);
// Validate Nested JSON
Schema schema = SchemaLoader.load(jsonSchema);
schema.validate(jsonObject);
System.out.println("â
Nested JSON is valid!");
} catch (Exception e) {
System.out.println("â Nested JSON validation failed: " + e.getMessage());
}
}
}
â Explanation:
-
nested_schema.json
should define the structure of nested objects. -
schema.validate()
ensures nested objects match the schema.
- â Always Validate JSON Before Parsing: Avoid exceptions by verifying JSON syntax.
- â Use Schema for Complex JSONs: For large JSON structures, define a strict schema.
- â
Catch Exceptions Gracefully: Wrap JSON operations in
try-catch
blocks. - â Consider Nested Validations: If your JSON contains nested objects, validate each level.
Error | Cause | Solution |
---|---|---|
MismatchedInputException |
Incorrect JSON structure | Validate and match Java classes. |
JsonProcessingException |
Malformed JSON | Check JSON syntax. |
ValidationException |
Schema mismatch | Update JSON schema. |
â You can now:
- Validate JSON syntax with Jackson.
- Use JSON Schema for advanced validation.
- Catch errors and handle them gracefully.
- Work confidently with complex JSON structures!