It sounds like you're trying to cap the size of the JSON data contained in the 'token' field of your request. You want it to be no more than 4000 characters, right? There's actually a way to handle this in Kotlin by creating your own validation annotation. Here's how:
First, you need to create the annotation itself:
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
@MustBeDocumented
@Constraint(validatedBy = [JsonNodeLengthValidator::class])
annotation class MaxJsonLength(
val message: String = "JSON Object is too big",
val groups: Array<KClass<*>> = [],
val payload: Array<KClass<out Payload>> = [],
val value: Int = 4000
)
Then, we'll make a custom validator for it:
import com.fasterxml.jackson.databind.node.ObjectNode
import javax.validation.ConstraintValidator
import javax.validation.ConstraintValidatorContext
class JsonNodeLengthValidator : ConstraintValidator<MaxJsonLength, ObjectNode> {
private var maxLength: Int = 0
override fun initialize(annotation: MaxJsonLength) {
this.maxLength = annotation.value
}
override fun isValid(node: ObjectNode?, context: ConstraintValidatorContext): Boolean {
return node?.toString()?.length ?: 0 <= maxLength
}
}
Finally, we'll use our shiny new validator annotation in your data class:
data class TokenRequest(
@NotEmpty(message = "id is mandatory")
open val id: String,
@NotEmpty(message = "gameId is mandatory")
open val game: String,
@NotEmpty(message = "gameType is mandatory")
open val type: String,
@NotEmpty(message = "gameDate is mandatory")
open val date: String,
@NotEmpty(message = "coupon is mandatory")
@MaxJsonLength(value = 4000, message = "Token JSON object is too big")
open val token: ObjectNode,
)
So there you have it! This makes sure that your TokenRequest
validation will fail if the JSON string of token
goes beyond 4000 characters. If it does, you'll get a validation error. Hope this helps!