我正在编写一个由mongodb支持的Play 2.3应用程序,它为一个angularjs客户端提供JSON服务。该应用程序正在从Rails移植,我的许多现有mongo文档有超过22个字段,这些字段阻止使用Json.format宏将它们序列化到/从案例类。我使用shapeless from this gist解决了这个问题(我还没有完全理解)。
现在我面临为客户端编写JSON“视图”的问题。并非我的文档中的所有数据都应该发送到客户端 - 哈希密码等。要发送正确的数据,我试图使用自定义写入,但我再次遇到21字段限制问题。例如,以下编译无法编译:
val viewWrites: Writes[User] = (
(__ \ "id").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String] and
(__ \ "u").write[String]
) { user: User =>
(user._id.toString(),
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username,
user.username)
}
错误
play.api.libs.functional.FunctionalBuilder[play.api.libs.json.OWrites]#CanBuild22[String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String,String] does not take parameters
如果我删除其中一个字段,它将正确编译。我意识到我可以将模型分解为几个部分,但我不想这样做,因为:
如何编写任意大小的JSON“视图”以便以预期的格式为我的现有客户端提供服务?
答案 0 :(得分:1)
声明您的写作如下:
implicit val viewWrites = new Writes[User] {
def writes(user: User) = Json.obj(
"id" -> user._id.toString(),
"u" -> user.username,
//repeat 20 times
"u" -> user.username)
}
基本上,您手动创建Writes [User]对象,并显式定义一个write方法,该方法接受User类型的单个参数,并返回一个JsObject。您可以根据需要包含/排除字段。