5

使用 scala play-json 库,如何拒绝包含未使用字段的 JsonObject?当我的 api 用户拼错一个字段或给出一个我会忽略的额外字段时,我想给出一个错误。在 java 版本中,我看到提到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
4

0 回答 0