【问题标题】:How to create generic implicit conversions for json marshalling如何为 json 编组创建通用隐式转换
【发布时间】:2018-08-20 18:37:03
【问题描述】:

我想将案例类的构造限制为某些类型,然后能够来回编组这些数据。

例如,假设我有一个接受“kind”参数的“home”案例类。我想将“种类”参数限制为已批准的住房类型列表,例如公寓、公寓等。

object Home {
  // this will create an implicit conversion to json object
  implicit lazy val jsFormat = Jsonx.formatCaseClass[Home]
}

case class Home(owner: String, kind: HousingType)

我现在需要的是一种方法来编组HousingType 的各种子类型。例如,这里有一些关系:

trait HousingType

case object Apartment extends HousingType

case object Condo extends HousingType

可以预见的是,在不指定隐式转换的情况下尝试使用它会产生以下错误:

"could not find implicit value for parameter helper: ... HousingType"

有没有办法为此创建一个通用的隐式转换?

【问题讨论】:

    标签: scala types marshalling


    【解决方案1】:

    您必须指定 JSON 编组器必须如何转换您的 case object,就像您拥有 case class 一样,JSON marshaller 遵循默认行为非常简单 - 从 case class 获取 JSON 字段名称及其类型.

    您需要指明如何直接编组/取消编组case object,例如通过隐式转换。

      implicit object HousingTypeMarshaller extends Writes[HousingType] {
        def writes(housingType: HousingType) = housingType match {
          case Apartment => Json.toJson("Apartment")
          case Condo => Json.toJson("Condo")
        }
      }
    

    附言我在这个例子中使用了常用的 play.json,因为我没有找到任何使用 Jsonx 的理由,建议你使用 Play Json 限制 22 个字段,通常 Play Json 适合使用 case object 的这种情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-03
      相关资源
      最近更新 更多