首页 > 解决方案 > json4s 使用默认值提取

问题描述

这是我的测试用例

case class WithDefaultValueHolder(values: Seq[WithDefaultValue])
case class WithDefaultValue(name: String, gender: String = "male")

it("default with valid json"){
  val res = WithDefaultValueHolder(Seq(WithDefaultValue("Bob")))
  parse("""{"values":[{"name":"Bob","gender":"male"}]}""").extract[WithDefaultValueHolder](
    DefaultFormats, Manifest.classType(classOf[WithDefaultValueHolder])) shouldBe (res)
}

下面的测试也通过了。它将格式错误的 json 视为默认值的有效 json。为什么?如何限制这种行为。如何在测试用例下失败?

it("default with invalid json"){
  val res = WithDefaultValueHolder(Seq(WithDefaultValue("Bob")))
  parse("""{"values":[{"name":"Bob","xyz":"abc"}]}""").extract[WithDefaultValueHolder](
    DefaultFormats, Manifest.classType(classOf[WithDefaultValueHolder])) shouldBe (res)
}

标签: scalajson4s

解决方案


推荐阅读