使用 Jackson 在 Java 中支持 JSON Schema?
JSON Schema 是针对基于 JSON 的格式的规范,用于定义 JSON 数据的结构。JsonSchema 类可以为 JSON 数据提供一份合约,说明给定应用程序需要采用哪些 JSON 数据以及如何与其交互。JsonSchema 可以定义 JSON 数据的验证、文档、超链接导航和交互控制。我们可以使用JsonSchemaGenerator的generateSchema()方法生成 JSON schema,此类封装了 JSON schema 生成功能。
语法
public JsonSchema generateSchema(Class<T> type) throws com.fasterxml.jackson.databind.JsonMappingException
示例
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jsonSchema.JsonSchema;
import com.fasterxml.jackson.module.jsonSchema.JsonSchemaGenerator;
import java.util.List;
public class JSONSchemaTest {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper jacksonObjectMapper = new ObjectMapper();
JsonSchemaGenerator schemaGen = new JsonSchemaGenerator(jacksonObjectMapper);
JsonSchema schema = schemaGen.generateSchema(Person.class);
String schemaString = jacksonObjectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema);
System.out.println(schemaString);
}
}
// Person class
class Person {
private String name;
private int age;
private List<String> courses;
private Address address;
public String getName() {
return name;
}
public int getAge(){
return age;
}
public List<String> getCourse() {
return courses;
}
public Address getAddress() {
return address;
}
}
// Address class
class Address {
private String firstLine;
private String secondLine;
private String thirdLine;
public String getFirstLine() {
return firstLine;
}
public String getSecondLine() {
return secondLine;
}
public String getThirdLine() {
return thirdLine;
}
}输出
{
"type" : "object",
"id" : "urn:jsonschema:Person",
"properties" : {
"name" : {
"type" : "string"
},
"age" : {
"type" : "integer"
},
"address" : {
"type" : "object",
"id" : "urn:jsonschema:Address",
"properties" : {
"firstLine" : {
"type" : "string"
},
"secondLine" : {
"type" : "string"
},
"thirdLine" : {
"type" : "string"
}
}
},
"course" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP