JSON Validation - potatoscript/json GitHub Wiki

✅ JSON Validation in Java: Ensure Your JSON is Correct! đŸŽ¯

Welcome to JSON Validation in Java – where we ensure that your JSON data is structured perfectly and error-free! 🎉đŸ•ĩī¸â€â™‚ī¸


đŸŽ¯ What is JSON Validation?

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).

đŸ”Ĩ 1. Why Validate JSON?

JSON data exchanged between systems can sometimes be:

  • ❌ Malformed (missing brackets, commas).
  • ❌ Containing unexpected or invalid values.
  • ❌ Missing required keys.

🎁 Common Errors:

  • {"name": "Lucy", "age": 26, } âžĄī¸ ❌ Trailing comma.
  • {"name": "Lucy", "age": "twenty-six"} âžĄī¸ ❌ Incorrect data type.

🧩 2. JSON Validation Methods in Java

There are multiple ways to validate JSON in Java:


âšĄī¸ a) Basic Syntax Validation

You can validate basic JSON syntax using ObjectMapper from the Jackson library.

📚 Add Jackson to Your Project

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.0</version>
</dependency>

đŸŽ¯ Example: Basic Syntax Validation with Jackson

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.

📌 b) JSON Schema Validation

To ensure JSON follows a defined schema, use the everit-org/json-schema library.


📚 Add JSON Schema Validator to Your Project

<dependency>
    <groupId>org.everit.json</groupId>
    <artifactId>org.everit.json.schema</artifactId>
    <version>1.14.3</version>
</dependency>

đŸŽ¯ 3. JSON Schema Basics

What is a JSON Schema?

  • 📚 Defines the structure, data types, and constraints of a JSON document.
  • ✅ Ensures that the JSON follows a predefined format.

📄 Sample JSON Schema:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "age"]
}

đŸŽ¯ 4. Validating JSON Against Schema in Java

đŸ”Ĩ Step 1: Create a JSON Schema File

Save the schema in user_schema.json:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" },
    "email": { "type": "string", "format": "email" }
  },
  "required": ["name", "age"]
}

đŸ”Ĩ Step 2: Validate JSON Using Everit Library

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.

🎨 5. Custom JSON Validation with Jackson Annotations

If you prefer to use annotations to validate JSON properties, you can annotate Java classes.


đŸŽ¯ Example: Using Jackson Annotations

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.

đŸ•ĩī¸â€â™‚ī¸ 6. Validating Nested JSON in Java

When dealing with nested JSON, make sure the structure is properly validated.


đŸŽ¯ Example: Nested JSON Validation

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.

🚀 7. Best Practices for JSON Validation in Java

  1. ✅ Always Validate JSON Before Parsing: Avoid exceptions by verifying JSON syntax.
  2. ✅ Use Schema for Complex JSONs: For large JSON structures, define a strict schema.
  3. ✅ Catch Exceptions Gracefully: Wrap JSON operations in try-catch blocks.
  4. ✅ Consider Nested Validations: If your JSON contains nested objects, validate each level.

đŸ•šī¸ 8. Common Errors and How to Handle Them

Error Cause Solution
MismatchedInputException Incorrect JSON structure Validate and match Java classes.
JsonProcessingException Malformed JSON Check JSON syntax.
ValidationException Schema mismatch Update JSON schema.

🎉 Conclusion: JSON Validation in Java – Mastered!

✅ 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!
âš ī¸ **GitHub.com Fallback** âš ī¸