пятница, 27 мая 2022 г.

Json model generator

 


<plugin>
<groupId>org.jsonschema2pojo</groupId>
<artifactId>jsonschema2pojo-maven-plugin</artifactId>
<version>1.1.1</version>
<configuration>
<sourceDirectory>${basedir}/src/main/resources/schema</sourceDirectory>
<targetPackage>ru.company.model</targetPackage>
<includeAdditionalProperties>false</includeAdditionalProperties>
<generateBuilders>true</generateBuilders>
<serializable>true</serializable>
<formatDates>true</formatDates>
<formatDateTimes>true</formatDateTimes>
<inclusionLevel>NON_EMPTY</inclusionLevel>
</configuration>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>

Валидация по json scheme

 

/**
* Получение строки из файла в ресурсах
*
* @param location- местоположение файла
* @return содержимое файла
*/
@SneakyThrows
public static String getJsonFromFile(String location) {
Resource resource = new DefaultResourceLoader().getResource(location);
return StreamUtils.copyToString(resource.getInputStream(), UTF_8);
}

/**
* Получение JSON схемы из файла
*
* @param source - местоположение файла с JSON схемой
* @return - схема
*/
@SneakyThrows
private static Schema getSchema(String source) {
JSONObject jsonObject = new JSONObject(new JSONTokener(new DefaultResourceLoader()
.getResource(source)
.getInputStream()));
return SchemaLoader.builder()
.schemaClient(SchemaClient.classPathAwareClient())
.schemaJson(jsonObject)
.resolutionScope(source)
.build().load().build();
}


private String SCHEMA_IN_RESOURCE = "classpath:/schema/MySchame.json";
Schema schema = getSchema(SCHEMA_IN_RESOURCE);
schema.validate(new org.json.JSONObject("{}"));