【问题标题】:How to convert a json to an entity in Play Framework REST API如何在 Play Framework REST API 中将 json 转换为实体
【发布时间】:2015-08-20 21:15:27
【问题描述】:

我刚刚开始使用 scala 和 play 框架,并陷入了这个看似简单的问题。

我有一个 REST 端点,我将向其发布一些 Json 对象。该 Json 对象需要转换为实体。

实体声明为case类类型,接收到的Json可以是case类中的任意一种。

我的问题是,我无法将 Json 转换为相应的实体类型,因为(根据教程)我需要在验证中编写 implicit Reads 并定义每个字段。

例如

implicit val emailReads: Reads[Email] = (
    (JsPath \ "from").read[String] and
      (JsPath \ "subject").read[String]
    )(Email.apply _)

适用于示例案例类电子邮件。但是当我有这样的案例类时:

abstract class Event
case class OneEventType(type : String) extends Event
case class TwoEventType(type : String, attribute : SomeType) extends Event

控制器方法基于事件工作:

def events = Action(BodyParsers.parse.json) { request =>
    val eventReceived = request.body.validate[Event]
    //do something
    Ok(Json.obj("status" ->"OK"))
}

我将如何验证事件并构造正确的事件对象,就像在 Reads 方法中我需要指定每个字段一样?

【问题讨论】:

    标签: json scala rest playframework-2.0 deserialization


    【解决方案1】:

    这应该可行,

    implicit val st: Reads[Event] = new Reads[Event] {
      def reads(json: JsValue): JsResult[Event] = {
        json match {
          case JsObject(Seq(("type", JsString(type)), ("attribute", JsString(attribute)))) =>  JsSuccess(TwoEventType(type, attribute))
          case o: JsObject if (o.value.get("type").isDefined) => JsSuccess(OneEventType(o.value.get("type")))
          case a: Any => JsError(a.toString())
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      我想你可以,在阅读中添加一个自定义过程。假设该属性是 Int 类型:

      abstract class Event
      case class OneEventType(type : String) extends Event
      case class TwoEventType(type : String, attribute : Int) extends Event
      
      implicit val eventReader: Reads[Event] = (
        (JsPath \ "type").read[String] and
        (JsPath \ "attribute").readNullable[Int]
      )((typeOp, attributeOp) => {
        if (attribute.isEmpty) OneEventType(typeOp.get())
        else TwoEventType(typeOp.get(), attributeOp.get())
      })
      

      (现在无法测试,所以我不确定它是否开箱即用)。

      【讨论】:

        猜你喜欢
        • 2013-09-09
        • 2015-03-05
        • 2014-12-26
        • 1970-01-01
        • 2022-12-12
        • 2016-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多