Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Jackson object mapper setting null instead of default values in case class

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 ''
like image 500
Nimrod007 Avatar asked Oct 01 '14 07:10

Nimrod007


2 Answers

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,"")
}
like image 164
Ion Cojocaru Avatar answered Sep 21 '22 00:09

Ion Cojocaru


Works with @JsonCreator annotation:

case class Person(id:Int,name:String = ""){
     @JsonCreator
     def this() = this(0,"")
}
like image 37
Vincent Avatar answered Sep 23 '22 00:09

Vincent