You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中实现数组型数据的JSON Schema验证需求

Java Implementation for JSON Schema Validation (Draft-04)

To validate your array-based JSON data against the provided schema, we'll use the Everit JSON Schema library—it’s a reliable choice with solid support for draft-04 schemas. Here’s a step-by-step implementation:

Step 1: Add Dependencies

First, include the necessary libraries in your project. For Maven, add these to your pom.xml:

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

For Gradle, add these lines to your build.gradle:

implementation 'org.everit.json:org.everit.json.schema:1.14.0'
implementation 'org.json:json:20231013'

Step 2: Complete Validation Code

This class loads your schema, tests both valid and invalid JSON inputs, and provides clear error feedback:

import org.everit.json.schema.Schema;
import org.everit.json.schema.ValidationException;
import org.everit.json.schema.loader.SchemaLoader;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.StringReader;

public class AccJsonValidator {

    public static void main(String[] args) {
        // Your provided JSON Schema
        String schemaString = """
                {
                  "$schema": "http://json-schema.org/draft-04/schema#",
                  "type": "object",
                  "properties": {
                    "acc": {
                      "type": "array",
                      "items": [
                        {
                          "type": "object",
                          "properties": {
                            "AccId": { "type": "integer" },
                            "accName": { "type": "string" },
                            "accSysName": { "type": "string" },
                            "accLName": { "type": "string" }
                          },
                          "required": [ "AccId", "accName", "accSysName", "accLName" ]
                        }
                      ]
                    }
                  },
                  "required": [ "acc" ]
                }
                """;

        // Example valid JSON input
        String validJson = """
                {
                  "acc": [
                    {
                      "AccId": 1001,
                      "accName": "Savings Account",
                      "accSysName": "CORE_SAVINGS",
                      "accLName": "Employee Savings Account"
                    },
                    {
                      "AccId": 1002,
                      "accName": "Checking Account",
                      "accSysName": "CORE_CHECKING",
                      "accLName": "Business Checking Account"
                    }
                  ]
                }
                """;

        // Example invalid JSON (missing "accLName" field)
        String invalidJson = """
                {
                  "acc": [
                    {
                      "AccId": 1001,
                      "accName": "Savings Account",
                      "accSysName": "CORE_SAVINGS"
                    }
                  ]
                }
                """;

        try {
            // Load and parse the schema
            JSONObject schemaJson = new JSONObject(new JSONTokener(new StringReader(schemaString)));
            Schema schema = SchemaLoader.load(schemaJson);

            // Validate valid input
            System.out.println("Testing valid JSON...");
            JSONObject validInput = new JSONObject(new JSONTokener(new StringReader(validJson)));
            schema.validate(validInput);
            System.out.println("✅ Valid JSON passed validation!");

            // Validate invalid input
            System.out.println("\nTesting invalid JSON...");
            JSONObject invalidInput = new JSONObject(new JSONTokener(new StringReader(invalidJson)));
            schema.validate(invalidInput);
            System.out.println("❌ Invalid JSON passed validation (this shouldn't happen!)");
        } catch (ValidationException e) {
            System.err.println("\n❌ Validation failed with errors:");
            e.getCausingExceptions().forEach(error -> System.err.println("- " + error.getMessage()));
        } catch (Exception e) {
            System.err.println("Error loading schema/JSON: " + e.getMessage());
        }
    }
}

Key Notes:

  • Schema Enforcement: The code ensures the root object has an acc array, and each array item includes all required fields with correct data types (e.g., AccId must be an integer, not a string).
  • Error Feedback: When validation fails, the ValidationException provides specific details about what went wrong (like missing fields or incorrect types).
  • Flexibility: You can replace the sample JSON strings with input from files or API responses by adjusting how you load the JSONObject.

内容的提问来源于stack exchange,提问作者siby21t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:33:14