【问题标题】:Scala Universal Serializer PlayFrameworkScala 通用序列化器 PlayFramework
【发布时间】:2014-09-24 19:24:00
【问题描述】:

我想制作我自己的不同列表类型(即 Group、GroupView、GroupItemsView)的通用 JSON 序列化器。所以,我定义了所有三个 Json.Format

  implicit val groupsFormat = Json.format[Group]
  implicit val groupsViewFormat = Json.format[GroupView]
  implicit val groupsItemsViewFormat = Json.format[GroupItemsView]

我的函数应该序列化不同的列表项:

  def groupViewToJson(entityList: List[Any]): JsValue = {
    val jsonList = Json.toJson(
      entityList.map( m => Json.toJson(m))
    )
    jsonList
  }

它仅在我为 entityList 定义特定列表类型时才有效。它不想使用 Any 类型。错误如下:

No Json serializer found for type Any. Try to implement an implicit Writes or Format for this type.

如何让 PlayFramework Scala JSON Serializer 普遍适用于我的类型?

【问题讨论】:

    标签: json scala playframework-2.0


    【解决方案1】:

    implicits 需要在编译时解析。因此,您的函数需要在编译期间为函数提供正确的隐式写入。您可以通过使用类型参数并接受隐式来做到这一点:

    def groupViewToJson[T](entityList: List[T])(implicit writer:Writes[T]): JsValue = {
        val jsonList = Json.toJson(
          entityList.map( m => Json.toJson(m))
        )
        jsonList
      }
    

    当调用groupViewToJson 时,隐式需要在范围内。一个完整的例子是:

    import play.api.libs.json._
    case class Group(name:String)
    case class GroupView(name:String, group: Group)
    
    implicit val groupsFormat = Json.format[Group]
    implicit val groupsViewFormat = Json.format[GroupView]
    //implicit val groupsItemsViewFormat = Json.format[GroupItemsView]
    
    
    def groupViewToJson[T](entityList: List[T])(implicit writer:Writes[T]): JsValue = {
        val jsonList = Json.toJson(
          entityList.map( m => Json.toJson(m))
        )
        jsonList
      }
    
    scala> val group = Group("MyGroup")
    group: Group = Group(MyGroup)
    
    scala> val groupView = GroupView("MyGroupView", group)
    groupView: GroupView = GroupView(MyGroupView,Group(MyGroup))
    
    scala> groupViewToJson(groupView :: Nil)
    res4: play.api.libs.json.JsValue = [{"name":"MyGroupView","group":{"name":"MyGroup"}}]
    

    【讨论】:

    • 谢谢它解决了我的问题!我完全忘记了类型参数化。
    • 另外,请注意 Json 已经为 Lists 提供了一个编写器,因为您有 case 类的编写器,所以除非您打算为您的 groupViewToJson 函数添加更多功能,否则您可以使用它来代替.
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    • 2018-10-24
    • 1970-01-01
    相关资源
    最近更新 更多