Issue
I have a service that receives a JSON with the following content:
{
"name": "test",
"gender": "NOT_VALID"
}
that JSON should be mapped to this object "Person"
data class Person(var name: String, var gender: Gender)
Person has a name (String) and Gender is an enum like:
enum class Gender() {
Male,
Female,
NotExplicit
}
I'm trying to implement a mapper that fails when the given Gender cant match with the explicit values that belongs to the enum. For example, if I try to do something like these:
ObjectMapper.personValidate(text: String): Person =
try {
val mapper = ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
val readValue: Person = mapper.readValue(text, Person::class.java)
val person: Person = mapper.readValue(ByteArrayInputStream(text.toByteArray()), Person::class.java)
person
} catch (e: Exception) {
when (e) {
is JsonParseException, is JsonMappingException -> {
throw PersonException()
}
else -> throw e
}
}
I'd expect an exception instead of the Person object.
This code right now is mapping gender to null when the value doesn't match.
Any clue?
Solution
You don't need to do anything. An exception will be thrown if you try to deserialize such a JSON into your Person
class, simply because Jackson will not be able to deserialize the String NOT_VALID
to a valid Gender
value.
Answered By - João Dias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.