Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

Java에서 Jackson 라이브러리로 JSON 스키마 생성하는 방법

JSON Schema는 JSON 데이터의 구조를 정의하기 위한 JSON 기반 형식의 표준 명세입니다. JsonSchema 클래스는 특정 애플리케이션에 어떤 JSON 데이터가 필요한지, 그리고 그 데이터와 어떻게 상호작용해야 하는지에 대한 일종의 계약(contract) 역할을 수행합니다. 또한 JsonSchema를 활용하면 JSON 데이터에 대한 유효성 검사(validation), 문서화(documentation), 하이퍼링크 탐색, 그리고 상호작용 제어까지 정의할 수 있습니다.

Jackson에서는 JsonSchemaGenerator 클래스가 JSON 스키마 생성 기능을 담당하며, 이 클래스가 제공하는 generateSchema() 메서드를 호출하여 스키마를 손쉽게 만들 수 있습니다.

문법(Syntax)

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

예제 코드

아래 예제에서는 ObjectMapper로부터 JsonSchemaGenerator를 생성한 뒤, Person 클래스를 기반으로 JSON 스키마를 생성하고 출력하는 과정을 보여줍니다.

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

실행 결과(Output)

위 코드를 실행하면 Person 객체의 필드 구조가 다음과 같은 JSON 스키마 형태로 변환되어 출력됩니다.

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

참고 사항

JSON 스키마 모듈을 사용하려면 Maven 프로젝트 기준으로 jackson-module-jsonSchema 의존성을 추가해야 합니다. 출력 결과에서 볼 수 있듯이 문자열 필드는 string, 정수 필드는 integer, 리스트 타입은 array로 자동 매핑되며, 중첩된 객체(Address) 역시 별도의 object 타입 스키마로 표현됩니다. 이렇게 생성된 스키마는 API 문서화나 클라이언트 측 입력값 검증 등 다양한 용도로 활용할 수 있습니다.