Tei*_*raz 7 json scala playframework playframework-2.2
rest api的JS客户端可以将int和string作为某个字段的值发送.
{
field1: "123",
field2: "456"
}
{
field1: 123,
field2: 456
}
Run Code Online (Sandbox Code Playgroud)
以下是应该转换json请求正文的case类的play动作:
case class Dto(field1: Int, field2: Int)
object Dto {
implicit val reads = Json.reads[Dto]
}
def create = Action.async(BodyParsers.parse.json) { implicit request =>
request.body.validate[Dto].map {
dto => someService.doStuff(dto).map(result => Ok(Json.toJson(result)))
}.recoverTotal {
e => jsErrorToBadRequest(e)
}
}
Run Code Online (Sandbox Code Playgroud)
如果我发送带有int值的json值,它可以正常工作.但是如果field1或field2是字符串("123","456"),它就会失败,因为request.body.validate需要Int.
但问题是JS客户端从输入字段发送值,输入字段转换为字符串.
处理整数或字符串的最佳方法是什么?(所以这个动作应该在两种情况下都将json转换为dto)
您还可以定义更宽容Reads[Int].并用它来定义你的Reads[Dto]
1)定义更宽容Reads[Int]:
import play.api.data.validation.ValidationError
import play.api.libs.json._
import scala.util.{Success, Try}
// Define a more tolerant Reads[Int]
val readIntFromString: Reads[Int] = implicitly[Reads[String]]
.map(x => Try(x.toInt))
.collect (ValidationError(Seq("Parsing error"))){
case Success(a) => a
}
val readInt: Reads[Int] = implicitly[Reads[Int]].orElse(readIntFromString)
Run Code Online (Sandbox Code Playgroud)
例子:
readInt.reads(JsNumber(1))
// JsSuccess(1,)
readInt.reads(JsString("1"))
// JsSuccess(1,)
readInt.reads(JsString("1x"))
// JsError(List((,List(ValidationError(List(Parsing error),WrappedArray())))
Run Code Online (Sandbox Code Playgroud)
2)使用你更宽容Reads[Int]来定义你的Reads[Dto]:
implicit val DtoReads =
(JsPath \ "field1").read[Int](readInt) and
(JsPath \ "field2").read[Int](readInt)
Run Code Online (Sandbox Code Playgroud)
编辑:与millhouse的解决方案的差异:
如果field1是一个字符串并且field2是一个使用此解决方案的int,那么你将获得JsSuccess一个JsError带有millhouse的解决方案
如果此解决方案的两个字段均无效,则JsError每个字段都会包含一个错误.使用millhouse的解决方案,您将收到第一个错误.
您需要Reads为您的Dto- 即 a定制实现Reads[Dto]。我总是喜欢从您通过的“内置”(宏生成)开始Json.reads[Dto]- 然后从那里开始;例如:
object Dto {
val basicReads = Json.reads[Dto]
implicit val typeCorrectingReads = new Reads[Dto]{
def reads(json: JsValue): JsResult[Dto] = {
def readAsInteger(fieldName:String):JsResult[Int] = {
(json \ fieldName).validate[String].flatMap { s =>
// We've got a String, but it might not be convertible to an int...
Try(s.toInt).map(JsSuccess(_)).getOrElse {
JsError(JsPath \ fieldName, s"Couldn't convert string $s to an integer")
}
}
}
basicReads.reads(json).orElse {
for {
f1 <- readAsInteger("field1")
f2 <- readAsInteger("field2")
} yield {
Dto(f1, f2)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
通过这样做,您就可以basicReads在“快乐的情况”中完成工作。如果不起作用,我们会尝试将这些字段视为String实例,然后最终尝试转换为Int.
JsResult请注意,只要有可能,我们就在“其他人”创建的a 范围内工作,因此我们很快就会失败。