Issue
What decorator can I put on the class field so that values other than true
and false
are not accepted in the request.
Now, any values can go into the request, including boolean
.
I can send false
, 0
and an empty string – it will be interpreted as false
.
I can send true
, all positive and negative numbers and it will be interpreted as true
.
What can I do to accept only true
and false
?
open class KdInfo : Info {
@Min(0)
var brutto: Long = 0
@NotNull
var isRefund: Boolean = false // this field can get not only boolean values from request
}
Solution
I found solution. Make custom JsonDeserializer and add it as decorator to field.:
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
class JsonBooleanDeserializer : JsonDeserializer<Boolean>() {
override fun deserialize(parser: JsonParser, context: DeserializationContext): Boolean {
return when (parser.text.toLowerCase()) {
"true" -> true
"false" -> false
else -> throw Exception()
}
}
}
open class KdInfo : Info {
@Min(0)
var brutto: Long = 0
@NotNull
@JsonProperty("refund")
@JsonDeserialize(using = JsonBooleanDeserializer::class)
var isRefund: Boolean = false // this field can get not only boolean values from request
}
Answered By - Anton Zotin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.