如何为 json 编组创建通用隐式转换

How to create generic implicit conversions for json marshalling

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

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

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"

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

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

您需要指明如何直接 marshall/unmarshall case object,例如通过隐式转换。

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

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