如何在Play 2.x中强制对JSON进行严格序列化 [英] How to enforce strict serialization of JSON in Play 2.x
问题描述
从JSON序列化为case类时,默认情况下允许Play的JSON序列化.例如.
Play's JSON serialization is by default permissive when serializing from JSON into a case class. For example.
case class Stuff(name: String, value: Option[Boolean])
implicit val stuffReads: Reads[Stuff] = (
( __ \ 'name).read[String] and
( __ \ 'value).readNullable[Boolean]
)(Stuff.apply _)
如果收到以下JSON:
If the following JSON was received:
{name: "My Stuff", value: true, extraField: "this shouldn't be here"}
它将以'JsSuccess'成功,并丢弃'extraField'.
It will succeed with a 'JsSuccess' and discard the 'extraField'.
如果存在未处理的"字段,是否可以构造Json Reads函数以使其返回JsError?
Is there a way to construct the Json Reads function to have it return a JsError if there are 'unhandled' fields?
推荐答案
您可以在执行自己的解码之前验证对象不包含多余的键:
You can verify that the object doesn't contain extra keys before performing your own decoding:
import play.api.data.validation.ValidationError
def onlyFields(allowed: String*): Reads[JsObject] = Reads.filter(
ValidationError("One or more extra fields!")
)(_.keys.forall(allowed.contains))
或者如果您不关心错误消息(无论如何也不是很有帮助):
Or if you don't care about error messages (and that one's not very helpful, anyway):
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)
重复不是很好,但是可以.
The repetition isn't very nice, but it works.
这篇关于如何在Play 2.x中强制对JSON进行严格序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!