【问题标题】:Play 2 - Can't return Json object in Response播放 2 - 无法在响应中返回 Json 对象
【发布时间】:2013-08-23 23:09:55
【问题描述】:

我正在尝试使用 Play 2.1.3 做一些 RESTFull Web 服务 POC

我有以下课程:

case class Student(id: Long,firstName: String,lastName: String) 

现在我想创建 RESTfull URI,它将获取 Json 序列化的 Student POJO 并返回相同的 POJO 作为响应。

implicit val studentReads = Json.reads[Student]
implicit val studentWrites = Json.writes[Student]


def updateStudent = Action(parse.json){
  request=>request.body.validate[Student].map{
    case xs=>Ok(xs)}.recoverTotal{
      e => BadRequest("Detected error:"+ JsError.toFlatJson(e))
    }
  } 

但我收到编译错误 -

Cannot write an instance of entities.Student to HTTP response. Try to define a 
     Writeable[entities.Student]

我刚刚提供了Writes[A] 作为隐式变量。

我还缺少什么?

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

    我认为问题在于 Ok() 方法无法确定需要将 Student 转换为 json,因为 Ok() 的参数可能会有所不同。

    1. 您可以返回Ok(Json.toJson(xs))
    2. 您可以明确指出所需的类型:Ok(xs: JsValue)

    并确保所有隐式都在范围内

    【讨论】:

    • 不断收到“定义可写”错误,Json.toJson 摆脱了这些错误。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 2019-06-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    相关资源
    最近更新 更多