have a case class Person with default param.
pass mapper a string missing a param, mapper sets it as null.
expecting it to set the default value
why is this ?
example :
@JsonIgnoreProperties(ignoreUnknown = true)
case class Person(id:Int,name:String="")
class MapperTest extends SpecificationWithJUnit {
"Mapper" should {
"use default param" in {
val personWithNoNameString = """{"id":1}"""
val mapper = new ObjectMapper();
mapper.registerModule(DefaultScalaModule)
val personWithNoName = mapper.readValue(personWithNoNameString,classOf[Person])
personWithNoName.name must be("")
}
}
}
get error :
'null' is not the same as ''
java.lang.Exception: 'null' is not the same as ''
Jackson mapper is using reflection to set the properties and disregards default values in the case class constructor. There is an open ticket, and it seems that the suggested solution in the comments does not work
case class Person(id:Int,name:String=""){
def this() = this(0,"")
}
Works with @JsonCreator annotation:
case class Person(id:Int,name:String = ""){
@JsonCreator
def this() = this(0,"")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With