在Java中,可以使用第三方庫(kù)如json-schema-validator或json-schema-validation來(lái)校驗(yàn)JSON數(shù)據(jù)的格式。以下是使用json-schema-validator的示例:
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.6</version>
</dependency>
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"age": {
"type": "integer"
}
},
"required": ["name", "age"]
}
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import java.io.File;
import java.io.IOException;
public class JsonValidator {
public static void main(String[] args) throws IOException, ProcessingException {
JsonNode jsonData = JsonLoader.fromFile(new File("data.json"));
JsonNode schemaData = JsonLoader.fromFile(new File("schema.json"));
JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
JsonSchema schema = factory.getJsonSchema(schemaData);
schema.validate(jsonData);
System.out.println("Data is valid!");
}
}
在這個(gè)示例中,我們加載了JSON數(shù)據(jù)和JSON Schema文件,并使用JsonSchema類進(jìn)行校驗(yàn)。如果數(shù)據(jù)符合JSON Schema的定義,那么校驗(yàn)通過(guò),否則會(huì)拋出異常。