json - 使用自定义表示在 Scala 中对 ADT 进行通用派生

标签 json scala circe generic-derivation

我正在解释a question from the circe Gitter channel在这里。

假设我有一个像这样的 Scala 密封特征层次结构(或 ADT):

sealed trait Item
case class Cake(flavor: String, height: Int) extends Item
case class Hat(shape: String, material: String, color: String) extends Item

...并且我希望能够在此 ADT 和 JSON 表示之间来回映射,如下所示:

{ "tag": "Cake", "contents": ["cherry", 100] }
{ "tag": "Hat", "contents": ["cowboy", "felt", "black"] }

默认情况下,circe 的通用派生使用不同的表示形式:

scala> val item1: Item = Cake("cherry", 100)
item1: Item = Cake(cherry,100)

scala> val item2: Item = Hat("cowboy", "felt", "brown")
item2: Item = Hat(cowboy,felt,brown)

scala> import io.circe.generic.auto._, io.circe.syntax._
import io.circe.generic.auto._
import io.circe.syntax._

scala> item1.asJson.noSpaces
res0: String = {"Cake":{"flavor":"cherry","height":100}}

scala> item2.asJson.noSpaces
res1: String = {"Hat":{"shape":"cowboy","material":"felt","color":"brown"}}

我们可以通过 circe-generic-extras 更接近:

import io.circe.generic.extras.Configuration
import io.circe.generic.extras.auto._

implicit val configuration: Configuration =
   Configuration.default.withDiscriminator("tag")

然后:

scala> item1.asJson.noSpaces
res2: String = {"flavor":"cherry","height":100,"tag":"Cake"}

scala> item2.asJson.noSpaces
res3: String = {"shape":"cowboy","material":"felt","color":"brown","tag":"Hat"}

……但这仍然不是我们想要的。

使用 circe 为 Scala 中的 ADT 派生此类实例的最佳方法是什么?

最佳答案

将案例类表示为 JSON 数组

首先要注意的是,circe-shapes 模块为 Shapeless 的 HList 提供了实例,这些实例使用类似于我们为案例类所需的数组表示形式。例如:

scala> import io.circe.shapes._
import io.circe.shapes._

scala> import shapeless._
import shapeless._

scala> ("foo" :: 1 :: List(true, false) :: HNil).asJson.noSpaces
res4: String = ["foo",1,[true,false]]

…Shapeless 本身提供了 case 类和 HList 之间的通用映射。我们可以将这两者结合起来以获得我们想要的案例类的通用实例:

import io.circe.{ Decoder, Encoder }
import io.circe.shapes.HListInstances
import shapeless.{ Generic, HList }

trait FlatCaseClassCodecs extends HListInstances {
  implicit def encodeCaseClassFlat[A, Repr <: HList](implicit
    gen: Generic.Aux[A, Repr],
    encodeRepr: Encoder[Repr]
  ): Encoder[A] = encodeRepr.contramap(gen.to)

  implicit def decodeCaseClassFlat[A, Repr <: HList](implicit
    gen: Generic.Aux[A, Repr],
    decodeRepr: Decoder[Repr]
  ): Decoder[A] = decodeRepr.map(gen.from)
}

object FlatCaseClassCodecs extends FlatCaseClassCodecs

然后:

scala> import FlatCaseClassCodecs._
import FlatCaseClassCodecs._

scala> Cake("cherry", 100).asJson.noSpaces
res5: String = ["cherry",100]

scala> Hat("cowboy", "felt", "brown").asJson.noSpaces
res6: String = ["cowboy","felt","brown"]

请注意,我使用 io.circe.shapes.HListInstances 来将 circe-shapes 所需的实例与自定义案例类实例捆绑在一起,以最大限度地减少我们的用户必须导入的东西(既是出于人体工程学的考虑,也是为了缩短编译时间)。

对 ADT 的通用表示进行编码

这是一个很好的第一步,但它并没有为我们提供 Item 本身所需的表示。为此,我们需要一些更复杂的机制:

import io.circe.{ JsonObject, ObjectEncoder }
import shapeless.{ :+:, CNil, Coproduct, Inl, Inr, Witness }
import shapeless.labelled.FieldType

trait ReprEncoder[C <: Coproduct] extends ObjectEncoder[C]

object ReprEncoder {
  def wrap[A <: Coproduct](encodeA: ObjectEncoder[A]): ReprEncoder[A] =
    new ReprEncoder[A] {
      def encodeObject(a: A): JsonObject = encodeA.encodeObject(a)
    }

  implicit val encodeCNil: ReprEncoder[CNil] = wrap(
    ObjectEncoder.instance[CNil](_ => sys.error("Cannot encode CNil"))
  )

  implicit def encodeCCons[K <: Symbol, L, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    encodeL: Encoder[L],
    encodeR: ReprEncoder[R]
  ): ReprEncoder[FieldType[K, L] :+: R] = wrap[FieldType[K, L] :+: R](
    ObjectEncoder.instance {
      case Inl(l) => JsonObject("tag" := witK.value.name, "contents" := (l: L))
      case Inr(r) => encodeR.encodeObject(r)
    }
  )
}

这告诉我们如何对Coproduct的实例进行编码,Shapeless将其用作Scala中密封特征层次结构的通用表示。这些代码一开始可能会令人生畏,但这是一种非常常见的模式,如果您花费大量时间使用 Shapeless,您会认识到此代码的 90% 本质上是样板文件,您在像这样归纳构建实例时会看到它们。

解码这些联积

解码实现有点差,甚至,但遵循相同的模式:

import io.circe.{ DecodingFailure, HCursor }
import shapeless.labelled.field

trait ReprDecoder[C <: Coproduct] extends Decoder[C]

object ReprDecoder {
  def wrap[A <: Coproduct](decodeA: Decoder[A]): ReprDecoder[A] =
    new ReprDecoder[A] {
      def apply(c: HCursor): Decoder.Result[A] = decodeA(c)
    }

  implicit val decodeCNil: ReprDecoder[CNil] = wrap(
    Decoder.failed(DecodingFailure("CNil", Nil))
  )

  implicit def decodeCCons[K <: Symbol, L, R <: Coproduct](implicit
    witK: Witness.Aux[K],
    decodeL: Decoder[L],
    decodeR: ReprDecoder[R]
  ): ReprDecoder[FieldType[K, L] :+: R] = wrap(
    decodeL.prepare(_.downField("contents")).validate(
      _.downField("tag").focus
        .flatMap(_.as[String].right.toOption)
        .contains(witK.value.name),
      witK.value.name
    )
    .map(l => Inl[FieldType[K, L], R](field[K](l)))
    .or(decodeR.map[FieldType[K, L] :+: R](Inr(_)))
  )
}

一般来说,我们的 Decoder 实现中会涉及更多的逻辑,因为每个解码步骤都可能失败。

我们的 ADT 代表

现在我们可以将它们全部包装在一起:

import shapeless.{ LabelledGeneric, Lazy }

object Derivation extends FlatCaseClassCodecs {
  implicit def encodeAdt[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    encodeRepr: Lazy[ReprEncoder[Repr]]
  ): ObjectEncoder[A] = encodeRepr.value.contramapObject(gen.to)

  implicit def decodeAdt[A, Repr <: Coproduct](implicit
    gen: LabelledGeneric.Aux[A, Repr],
    decodeRepr: Lazy[ReprDecoder[Repr]]
  ): Decoder[A] = decodeRepr.value.map(gen.from)
}

这看起来与上面的 FlatCaseClassCodecs 中的定义非常相似,并且想法是相同的:我们通过构建实例来定义数据类型(案例类或 ADT)的实例这些数据类型的通用表示。请注意,我扩展了 FlatCaseClassCodecs,再次最大限度地减少用户的导入。

在行动

现在我们可以像这样使用这些实例:

scala> import Derivation._
import Derivation._

scala> item1.asJson.noSpaces
res7: String = {"tag":"Cake","contents":["cherry",100]}

scala> item2.asJson.noSpaces
res8: String = {"tag":"Hat","contents":["cowboy","felt","brown"]}

...这正是我们想要的。最好的部分是,这适用于 Scala 中的任何密封特征层次结构,无论它有多少个案例类或这些案例类有多少个成员(尽管一旦您进入数十个其中之一,编译时间就会开始受到影响) ),假设所有成员类型都有 JSON 表示形式。

关于json - 使用自定义表示在 Scala 中对 ADT 进行通用派生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52117213/

相关文章:

php - 我有来自 mysql 的数据,但错误地转换为 JSON

scala - 如何在 typesafeconfig 中将 ConfigValue 转换为 List[ConfigObject]

json - 如何设置类中属性的值并使用 lift json 将其转换为 json

json - 类型 io.circe.Encoder[scala.collection.immutable.Map[Int,Any]] 的发散隐式扩展

javascript - 带有 Twitter Bootstrap 的 JSON 的 AngularJS 菜单和子菜单

php - 如何将带有数据的 http header 发送到 rest Api codeigniter?

python - 如何通过 python 将 JSON 数据附加到存储在 Azure Blob 存储中的现有 JSON 文件?

scala - 在 Scalaz 中将 Free 与非仿函数一起使用

json - 使用 circe 编码为 JSON 时出现 StackOverflowError

scala - 将 Json4S 迁移到 Circe