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

问题描述 投票:5回答:2

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

传递mapper一个缺少param的字符串,mapper将其设置为null。

期望它设置默认值

为什么是这样 ?

例如:

@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("")
     }
  }
}

得到错误:

'null' is not the same as ''
java.lang.Exception: 'null' is not the same as ''
json scala jackson mapper
2个回答
0
投票

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

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

0
投票

适用于@JsonCreator注释:

case class Person(id:Int,name:String = ""){
     @JsonCreator
     def this() = this(0,"")
}
© www.soinside.com 2019 - 2024. All rights reserved.