Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

Java에서 Jackson을 사용하는 JSON 스키마 지원?


JSON 스키마는 JSON 데이터의 구조를 정의하기 위한 JSON 기반 형식에 대한 사양입니다. JsonSchema 클래스는 주어진 애플리케이션에 필요한 JSON 데이터와 이 데이터와 상호 작용하는 방법에 대한 계약을 제공할 수 있습니다. JsonSchema 검증, 문서화, 하이퍼링크 탐색을 정의할 수 있습니다. 및 상호작용 제어 JSON 데이터의. generateSchema()를 사용하여 JSON 스키마를 생성할 수 있습니다. JsonSchemaGenerator 메소드 , 이 클래스는 JSON 스키마 생성 기능을 래핑합니다.

구문

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