2014-10-01 36 views
5

有一个具有默认参数的案例类Person。斯卡拉杰克逊对象映射器设置为null,而不是默认值,如果类

传递映射器一个字符串缺少一个参数,映射器将其设置为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 '' 

回答

0

杰克逊映射器使用反射来设置的属性,并在壳体类构造忽略默认值。 有一个开放的ticket,并似乎在评论中所建议的解决方案不起作用

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

不会编译(预期诠释了空) – Nimrod007 2014-10-01 11:59:45

+0

更新的响应,null.asInstanceOf [INT]为0,否则使用选项[Int] – 2014-10-01 13:36:58

+0

仍然不能正常工作,运行测试会给出null – Nimrod007 2014-10-01 13:38:49