Scala Jackson对象映射器在case类中设置null而不是默认值

时间:2021-02-19 18:02:16

have a case class Person with default param.

有一个具有默认参数的案例类Person。

pass mapper a string missing a param, mapper sets it as null.

传递mapper一个缺少param的字符串,mapper将其设置为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 ''

1 个解决方案

#1


0  

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

Jackson映射器使用反射来设置属性并忽略case类构造函数中的默认值。有一个打开的票证,似乎评论中建议的解决方案不起作用

case class Person(id:Int,name:String=""){
     def this() = this(0,"")
}

#1


0  

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

Jackson映射器使用反射来设置属性并忽略case类构造函数中的默认值。有一个打开的票证,似乎评论中建议的解决方案不起作用

case class Person(id:Int,name:String=""){
     def this() = this(0,"")
}