为密封特征层次结构编写DecodeJson?

时间:2017-10-17 20:35:32

标签: scala argonaut

假设:

import argonaut._
import Argonaut._
import ArgonautShapeless._

sealed trait Parent
case class Foo(x: Int)    extends Parent
case class Bar(y: String) extends Parent

我试图定义DecodeJson[Parent]

implicit val parentDecodeJson: DecodeJson[Parent] = 
   DecodeJson(c => c.focus.objectFields match {
       case Some("x" :: _) => implicitly[DecodeJson[Foo]].decode(c)
      case _                => implicitly[DecodeJson[Bar]].decode(c)
   })

然而,由于argonaut.DecodeResult是不变的,因此失败了。

<console>:42: error: type mismatch;
 found   : argonaut.DecodeResult[Foo]
 required: argonaut.DecodeResult[Parent]
Note: Foo <: Parent, but class DecodeResult is invariant in type A.
You may wish to define A as +A instead. (SLS 4.5)
              case Some("x" :: _) => implicitly[DecodeJson[Foo]].decode(c)
                                                                       ^
<console>:43: error: type mismatch;
 found   : argonaut.DecodeResult[Bar]
 required: argonaut.DecodeResult[Parent]
Note: Bar <: Parent, but class DecodeResult is invariant in type A.
You may wish to define A as +A instead. (SLS 4.5)
             case _     => implicitly[DecodeJson[Bar]].decode(c)
                                                             ^

所以,我想出了:

implicit val parentDecodeJson: DecodeJson[Parent] = 
   DecodeJson(c => c.focus.objectFields match {
       case Some("x" :: _) => implicitly[DecodeJson[Foo]].decode(c).flatMap{a => DecodeResult.ok(a)}
      case _     => implicitly[DecodeJson[Bar]].decode(c).flatMap{a => DecodeResult.ok(a)}
   })

这似乎有效:

scala> Json.obj( ("x", jNumber(42)) ).as[Parent]
res2: argonaut.DecodeResult[Parent] = DecodeResult(Right(Foo(42)))

scala> Json.obj( ("y", jString("hi!")) ).as[Parent]
res3: argonaut.DecodeResult[Parent] = DecodeResult(Right(Bar(hi!)))

有更清洁的方式吗?

1 个答案:

答案 0 :(得分:0)

您无需定义自己的含义:

println(EncodeJson.of[Parent].encode(Bar("a")))//{"Bar":{"y":"a"}}
println(EncodeJson.of[Parent].apply(Bar("a")))//{"Bar":{"y":"a"}}
println(Bar("a").asJson)//{"y":"a"}
println((Bar("a"): Parent).asJson)//{"Bar":{"y":"a"}}
println("{\"Bar\":{\"y\":\"a\"}}".decode[Parent])//Right(Bar(a))
println("{\"Bar\":{\"y\":\"a\"}}".decodeOption[Parent])//Some(Bar(a))

或者我是否误解了你的目标?