Зависимость, используемая для проверки схемы:
Код: Выделить всё
com.networknt
json-schema-validator
1.4.0
Код: Выделить всё
@Bean
public JsonSchema jsonSchema() {
return JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V202012)
.getSchema(getClass().getClassLoader().getResourceAsStream(“/main.json”));
}
Код: Выделить всё
@Autowired
private JsonSchema jsonSchema;
@Autowired
private ObjectMapper objectMapper;
@PostMapping("/validate")
public void validate(@RequestBody RequestDto request) {
JsonNode jsonNode = objectMapper.valueToTree(request);
Set validationMessages = jsonSchema.validate(jsonNode);
if (!validationMessages.isEmpty()) {
throw new JsonSchemaValidationException(validationMessages);
}
log.info("Validation Passed");
}
Код: Выделить всё
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ResponsePayload",
"description": "Payload object response",
"type": "object",
"properties": {
"objectA": {
"$ref": "classpath:/sub1.json"
},
"objectB": {
"$ref": "classpath:/sub2.json"
},
"objectC": {
"$ref": "classpath:/sub3.json"
}
},
"required": [
"objectA",
"objectB"
]
}
Код: Выделить всё
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Sub1Payload",
"description": "Sub payload 1",
"type": "object",
"properties": {
"name": {
"type": "string"
},
"number": {
"type": "integer"
},
"type-emp-land": {
"type": "object",
"properties": {
"location": {
"type": "string"
},
"area": {
"type": "string"
}
}
}
},
"required": [
"name",
"number",
"type-emp-land"
]
}
Код: Выделить всё
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Sub2Payload",
"description": "Sub payload 2",
"type": "object",
"properties": {
"location": {
"type": "string"
},
"area": {
"type": "string"
},
"radius": {
"type": "object",
"properties": {
"cm": {
"type": "integer"
},
"km": {
"type": "integer"
}
}
},
"type-emp-land-location": {
"$ref": "classpath:/sub1.json#/properties/type-emp-land/properties/location"
}
},
"required": [
"location",
"area"
],
"allOf": [
{
"if": {
"properties": {
"type-emp-land-location": {
"const": "InsideNothingHall"
}
}
},
"then": {
"required": [
"radius"
]
}
}
]
}
Код: Выделить всё
{
"objectA": {
"name": "Wired",
"number": 1234,
"type-emp-land": {
"location": "InsideNothingHall",
"area": "Inside square"
}
},
"objectB": {
"location": "Mid",
"area": "50 cm"
}
}
Код: Выделить всё
JsonSchemaValidationException with required field 'radius' missing message.
Код: Выделить всё
JsonSchemaValidationException with required field 'radius' missing message
Код: Выделить всё
{
"objectA": {
"name": "Wired",
"number": 1234,
"type-emp-land": {
"location": "OutTown",
"area": "Inside square"
}
},
"objectB": {
"location": "Mid",
"area": "50 cm"
}
}
Код: Выделить всё
Validation Passed - logВывод:
Код: Выделить всё
JsonSchemaValidationException with required field 'radius' missing message
Что мне здесь не хватает?
Подробнее здесь: https://stackoverflow.com/questions/790 ... -schema-dr
Мобильная версия