我有一个 Controller 类,我在其中放置了一个写入对象来序列化我的用户对象。不幸的是,检索 user.getId 时出现错误:
type mismatch; found : Long required: play.api.libs.json.Json.JsValueWrapper
Note: implicit value userWrites is not applicable here because it comes
after the application point and it lacks an explicit result type
这是我的代码:
object UsersController extends Controller {
implicit val userWrites = new Writes[User] {
def writes(user: User) = Json.obj(
"id" -> user.getId,
"username" -> user.getUsername
)
}
def users = Action { implicit request =>
Ok(views.html.users())
}
}
我不确定为什么错误显示“注意:隐式值 userWrites 在此不适用...”,因为如果我删除 user.getId 部分,错误就会消失。
我需要做什么才能消除此错误并为我的 User 类正确创建 Writes 对象。
最佳答案
Java Long 不是 Scala Long,Play 的 Scala JSON 序列化器仅支持 Scala 类型。您可以通过 Long2long
显式转换:
implicit val userWrites = new Writes[User] {
def writes(user: User) = Json.obj(
"id" -> Long2long(user.getId),
"username" -> user.getUsername
)
}
关于json - 使用 ScalaJson 序列化解决类型不匹配问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26808764/