gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:09:17 25 4
gpt4 key购买 nike

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

向映射器传递一个缺少参数的字符串,映射器将其设置为空。

期望它设置默认值

为什么是这样 ?

例子 :

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

最佳答案

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

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

关于json - Scala Jackson 对象映射器在 case 类中设置 null 而不是默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26136331/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com