从JSON序列化为case类时,默认情况下允许Play的JSON序列化。例如。

case class Stuff(name: String, value: Option[Boolean])

implicit val stuffReads: Reads[Stuff] = (
  ( __ \ 'name).read[String] and
  ( __ \ 'value).readNullable[Boolean]
)(Stuff.apply _)

如果收到以下JSON:
{name: "My Stuff", value: true, extraField: "this shouldn't be here"}

它将以“JsSuccess”成功,并丢弃“extraField”。

如果存在“未处理的”字段,是否可以构造Json Reads函数以使其返回JsError?

最佳答案

您可以在执行自己的解码之前验证对象不包含额外的键:

import play.api.data.validation.ValidationError

def onlyFields(allowed: String*): Reads[JsObject] = Reads.filter(
  ValidationError("One or more extra fields!")
)(_.keys.forall(allowed.contains))

或者,如果您不关心错误消息(无论如何也不是很有帮助):
def onlyFields(allowed: String*): Reads[JsObject] =
  Reads.verifying(_.keys.forall(allowed.contains))

接着:
implicit val stuffReads: Reads[Stuff] = onlyFields("name", "value") andThen (
  (__ \ 'name).read[String] and
  (__ \ 'value).readNullable[Boolean]
)(Stuff)

重复不是很好,但是可以。

10-06 08:40