简体   繁体   中英

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 ''

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,"")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM