Skip to content
Anjunar/ DOCS

Validation

Every value is checked with Bean Validation before it is set. All violations of one call come back together, each with its path.

Constraints

Annotations on the model

The mapper calls validateValue for each property with the value from the JSON. A value that violates a constraint is not set.

scala
import jakarta.validation.constraints.{NotBlank, Size} class UserDto extends DTO { @(NotBlank @field) @(Size @field)(max = 80) @(JsonbProperty @field) var name: String = null }
Errors

One exception with every violation

After the whole graph was visited, the mapper throws ErrorRequestException if anything was rejected. Each ErrorRequest carries a path through the graph, collection indexes included, and the constraint's message.

scala
import com.anjunar.json.mapper.ErrorRequestException try JsonMapper.deserialize(JsonParser.parse("""{"name": ""}"""), target, TypeResolver.resolve(classOf[UserDto]), null, loader, inject, validator) catch case error: ErrorRequestException => error.errors.forEach(request => println(s"${request.path} ${request.message}"))
Output
[name] must not be blank

ErrorRequest is itself annotated for JSON, so a REST endpoint can serialize the list as its error response.

Transactions

Valid values are already set

Validation runs per property. When the exception is thrown, the valid properties of the same call have been written already.

Roll back on errors

Deserialize managed entities inside a transaction and roll it back on ErrorRequestException, or work on a copy. Otherwise a rejected request leaves a partly updated object behind.