itsource

Java 클래스에서 JSON 스키마 생성

mycopycode 2023. 3. 18. 08:36
반응형

Java 클래스에서 JSON 스키마 생성

POJO 클래스가 있습니다.

public class Stock {
 int id;
 String name;
 Date date;
}

다음과 같이 POJO를 JSON 스키마로 변환할 수 있는 주석 또는 개발 프레임워크/API가 있습니까?

{"id":
      {             
        "type" : "int"
      },
"name":{   
        "type" : "string"
       }
"date":{
        "type" : "Date"
      }
}

또한 스키마를 확장하여 다음과 같은 정보를 추가할 수 있습니다."Required" : "Yes"POJO에 주석 또는 설정을 지정하여 각 필드에 대한 설명으로 다음과 같이 JSON 스키마를 생성할 수 있습니다.

{"id":
      {             
        "type" : "int",
        "Required" : "Yes",
        "format" : "id must not be greater than 99999",
        "description" : "id of the stock"
      },
"name":{   
        "type" : "string",
        "Required" : "Yes",
        "format" : "name must not be empty and must be 15-30 characters length",
        "description" : "name of the stock"
       }
"date":{
        "type" : "Date",
        "Required" : "Yes",
        "format" : "must be in EST format",
        "description" : "filing date of the stock"
      }
}

Jackson JSON Schema 모듈 중 하나가 이러한 도구입니다.

https://github.com/FasterXML/jackson-module-jsonSchema

Jackson databind의 POJO inspection을 사용하여 잭슨 주석을 고려하여 POJO 속성을 트래버스하고 JSON Schema 개체를 생성합니다. JSON은 JSON으로 일련화되거나 다른 용도로 사용될 수 있습니다.

Java JSON Schema Generator : https://github.com/victools/jsonschema-generator

Jackson을 사용하여 Java 클래스에서 JSON 스키마(Draft 6, Draft 7 또는 Draft 2019-09)를 만듭니다.

JJSchema를 사용합니다.드래프트 4 준거 JSON 스키마를 생성할 수 있습니다.상세한 것에 대하여는, http://wilddiary.com/generate-json-schema-from-java-class/ 를 참조해 주세요.

Jackson Schema 모듈도 스키마를 생성할 수 있지만 현재로선 드래프트3 준거 스키마만 생성할 수 있습니다.

public static String getJsonSchema(Class clazz) throws IOException {
         Field[] fields = clazz.getDeclaredFields();
         List<Map<String,String>> map=new ArrayList<Map<String,String>>();
         for (Field field : fields) {
             HashMap<String, String> objMap=new  HashMap<String, String>();
             objMap.put("name", field.getName());
             objMap.put("type", field.getType().getSimpleName());
             objMap.put("format", "");
             map.add(objMap);
         }
         ObjectMapper mapper = new ObjectMapper();
         String json = mapper.writeValueAsString(map);

       return json;
    }

언급URL : https://stackoverflow.com/questions/26199716/generate-json-schema-from-java-class

반응형