Using the scala play-json library, how can I reject a JsonObject that contains unused fields? I want to give an error when my api users misspell a field or give an extra field that I would ignore. In the java version, I see mention of DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES
, but I don’t see that in the scala version.
Here is my desired unit test:
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]
}
}
and this 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