7

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 ''
Nimrod007
  • 9,825
  • 8
  • 48
  • 71

3 Answers3

2

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,"")
}
Ion Cojocaru
  • 2,583
  • 15
  • 16
1

Works with @JsonCreator annotation:

case class Person(id:Int,name:String = ""){
     @JsonCreator
     def this() = this(0,"")
}
Vincent
  • 433
  • 3
  • 10
0

The above worked for me, but I thought it was less than ideal to define defaults twice. There is another way which also works, avoiding the need for duplicate default declarations.

case class Person(id:Int, name: String = "")

object Person {
  @JsonCreator
  def default = Person(0)
}
Jodiug
  • 5,425
  • 6
  • 32
  • 48