使用scala play-json库,如何拒绝包含未使用字段的JsonObject?当我的api用户拼错字段或给出一个我忽略的额外字段时,我想给出错误。在java版本中,我看到mention of DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
,但我没有在scala版本中看到它。
这是我想要的单元测试:
import org.scalatest._
import play.api.libs.json.{JsError, JsSuccess, Json}
case class MyStruct(a: Int, b: String)
object MyStruct {
import play.api.libs.functional.syntax._
import play.api.libs.json._ // Combinator syntax
implicit val writes: Writes[MyStruct] = Json.writes[MyStruct]
implicit val reads: Reads[MyStruct] = Json.reads[MyStruct]
}
class MyStructTest extends FlatSpec with Matchers {
"MyStruct reader" should "read json" in {
val x = Json.parse("{\"a\": 3, \"b\": \"hi\"}").validate[MyStruct]
x should be(
JsSuccess(
MyStruct(
a = 3,
b = "hi"
)
)
)
}
it should "reject json with unused fields" in {
val y = Json.parse("{\"a\": 3, \"b\": \"hi\", \"c\": 8239}").validate[MyStruct]
y shouldBe a [JsError]
}
}
和这个build.sbt
name := "scratch"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies += "com.typesafe.play" %% "play-json" % "2.5.0"
libraryDependencies += "org.scalatest" %% "scalatest" % "2.2.6" % Test