播放框架:JSON读取单个属性的案例类 [英] Play framework: JSON Reads for a single-attribute case class

查看:71
本文介绍了播放框架:JSON读取单个属性的案例类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为包含单个属性的案例类创建隐式的JSON读取,但出现错误读取[无]不符合预期类型".这是代码:

I'm trying to create a JSON Reads implicit for a case class that contains a single attribute, but I'm getting an error "Reads[Nothing] doesn't conform to expected type". Here's teh codes:

import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._
import play.api.libs.json.{JsPath, Json, Reads}

case class Feedback(message: String)
object Feedback {
  implicit val reads: Reads[Feedback] = (
      (JsPath \ "message").read[String](maxLength[String](2000))
    )(Feedback.apply _)
}

为什么这不起作用?如果我将额外的属性添加到case类中,并且多个.read调用与and一起加入,那么它将起作用...

Why isn't this working? If I add extra attributes to the case class and multiple .read calls joined with and it works...

推荐答案

Json组合器不适用于单个字段案例类.

Json combinators doesn't work for single field case class.

您可以执行以下操作:

import play.api.libs.json.Reads._
import play.api.libs.json.{__, Reads}

case class Feedback(message: String)
object Feedback {
  implicit val reads: Reads[Feedback] = (__ \ "message")
    .read[String](maxLength[String](2000)).map {message => Feedback(message)}
}

这是由于当前Macro实施中的限制所致.您可以在此处了解更多信息: Pacal是此书的作者API

It's because of a limitation in the current Macro implementation. You can read more about it here: Pacal is the writer of this API

这篇关于播放框架:JSON读取单个属性的案例类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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