Computer >> Máy Tính >  >> Lập trình >> Java

Lược đồ JSON Hỗ trợ sử dụng Jackson trong Java?


JSON Schema là một đặc tả cho định dạng dựa trên JSON để xác định cấu trúc của dữ liệu JSON. JsonSchema lớp có thể cung cấp một hợp đồng cho dữ liệu JSON nào được yêu cầu cho một ứng dụng nhất định và cách tương tác với nó. JsonSchema có thể xác định xác thực, tài liệu, điều hướng siêu liên kết kiểm soát tương tác dữ liệu JSON. Chúng tôi có thể tạo lược đồ JSON bằng cách sử dụng createSchema () phương thức của JsonSchemaGenerator , lớp này bao bọc chức năng tạo lược đồ JSON.

Cú pháp

public JsonSchema generateSchema(Class<T> type) throws com.fasterxml.jackson.databind.JsonMappingException

Ví dụ

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;
   }
}

Đầu ra

{
   "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"
         }
      }
   }
}