我在 Scala 中做一件事。我有以下案例类:
import shapeless._
case class Foo(param1: String, param2: HList)
我想使用Circe获得这种类型的 JSON 表示。我还想将生成的 JSON 字符串映射回类型。
circe-shapes 模块会自动推导 HList,从 HList 到 JSON 并返回很容易。看这个例子:
scala> import shapeless._
import shapeless._
scala> import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
scala> import io.circe.shapes._
import io.circe.shapes._
scala> val myList = 30 :: "car" :: HNil
myList: shapeless.::[Int,shapeless.::[String,shapeless.HNil]] = 30 :: car :: HNil
scala> val listJson = myList.asJson
listJson: io.circe.Json =
[
30,
"car"
]
scala> listJson.as[HList] // won't work
<console>:32: error: could not find implicit value for parameter d: io.circe.Decoder[shapeless.HList]
listJson.as[HList]
^
scala> listJson.as[::[Int, ::[String, HNil]]]
res3: io.circe.Decoder.Result[shapeless.::[Int,shapeless.::[String,shapeless.HNil]]] = Right(30 :: car :: HNil)
包含“标准”类型的案例类也很简单:
scala> case class Bar(one: String, a: Double, andAn: Int)
defined class Bar
scala> val myBar = Bar("pie", 4.35, 2)
myBar: Bar = Bar(pie,4.35,2)
scala> val barJson = myBar.asJson
barJson: io.circe.Json =
{
"one" : "pie",
"a" : 4.35,
"andAn" : 2
}
scala> barJson.as[Bar]
res5: io.circe.Decoder.Result[Bar] = Right(Bar(pie,4.35,2))
明确 HList 的类型可以创造奇迹,但这有点违背 HList 的目的:
scala> case class Foo2(a: String, b: ::[Int, ::[String, HNil]])
defined class Foo2
scala> val myFoo2 = Foo2("ark", 42 :: "meg" :: HNil)
myFoo2: Foo2 = Foo2(ark,42 :: meg :: HNil)
scala> val foo2Json = myFoo2.asJson
foo2Json: io.circe.Json =
{
"a" : "ark",
"b" : [
42,
"meg"
]
}
scala> foo2Json.as[Foo2]
res8: io.circe.Decoder.Result[Foo2] = Right(Foo2(ark,42 :: meg :: HNil))
Circe 可以解码任意 HList 吗?