播放Json单字段读取验证器 [英] Play Json Single Field Reads Validator

查看:102
本文介绍了播放Json单字段读取验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为传入的Json Play添加简单的验证.基于这个问题,我尝试编写:

I'm trying to add simple validation to incoming Json in Play. Based on this question, I tried writing:

case class ApiData(data: String)

def maxLengthValidator = Reads.StringReads.filter(ValidationError("Error"))(_.length < 100)

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator)
)(ApiData.apply _)

这不能编译,产生错误:

This does not compile, producing the error:

type mismatch;
[error]  found   : String => ApiData
[error]  required: play.api.libs.json.Reads[?]
[error]     )(ApiData.apply _)
[error]                        ^
[error] one error found

但是如果我添加第二个字段,它将编译:

But if I add a second field, it does compile:

case class ApiData(data: String, __doNotUse: Option[Int])

implicit val ApiDataReads: Reads[ApiData] = (
  (JsPath \ "data").read[String](maxLengthValidator) and
  (JsPath \ "__doNotUse").readNullable[Int]
)(ApiData.apply _)

我需要做什么才能使它仅在单个字段中起作用?

What do I need to do to get this working with just a single field?

推荐答案

由于您只有一个字段,因此不需要使用组合语法来创建读取,因此可以使用已经在Reads上定义的函数建立你想要的那个.

Since you only have a single field, you don't need the combinator syntax to create a reads, you can just use the functions already defined on Reads to build the one you want.

def maxLengthValidator = Reads.of[String].filter(ValidationError("Error"))(_.length < 100)

case class ApiData(data: String)

object ApiData {

  implicit val reads: Reads[ApiData] = (__ \ "data").read(maxLengthValidator).map(ApiData.apply _)

}

Reads[String]开始,添加一些验证(filter),然后将有效结果转换为您自己的丰富类型(map).

You start with a Reads[String], add some validation (filter) and then transform valid results to your own rich type (map).

这篇关于播放Json单字段读取验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆