簡體   English   中英

Argonaut:解碼多態數組

[英]Argonaut: decoding a polymorphic array

我正在嘗試編寫DecodeJson[T]的JSON對象包含一個不同“類型”的數組(意味着其元素的JSON結構不同)。 唯一的共同特征是type字段,可用於區分類型。 所有其他領域都不同。 例:

{
    ...,
    array: [
        { type: "a", a1: ..., a2: ...},
        { type: "b", b1: ...},
        { type: "c", c1: ..., c2: ..., c3: ...},
        { type: "a", a1: ..., a2: ...},
        ...
    ],
    ...
}

使用argonaut,是否可以將JSON數組映射到Scala Seq[Element] ,其中ElementElementAElementB等類型的合適案例類的超類型?

我用play-json做了同樣的事情,這很容易(基本上是一個Reads[Element] ,用於評估type字段並相應地轉發到更具體的Reads )。 但是,我找不到與argonaut這樣做的方法。


編輯:示例

Scala類型(我希望使用):

case class Container(id: Int, events: List[Event])

sealed trait Event
case class Birthday(name: String, age: Int) extends Event
case class Appointment(start: Long, participants: List[String]) extends Event
case class ... extends Event

JSON實例(不在我的控制之下):

{
   "id":1674,
   "events": {
      "data": [
         {
            "type": "birthday",
            "name": "Jones Clinton",
            "age": 34
         },
         {
            "type": "appointment",
            "start": 1675156665555,
            "participants": [
               "John Doe",
               "Jane Doe",
               "Foo Bar"
            ]
         }
      ]
   }
}

您可以創建一個小函數來幫助您構建處理此格式的解碼器。

請參閱下面的示例。

import argonaut._, Argonaut._

def decodeByType[T](encoders: (String, DecodeJson[_ <: T])*) = {
  val encMap = encoders.toMap

  def decoder(h: CursorHistory, s: String) =
    encMap.get(s).fold(DecodeResult.fail[DecodeJson[_ <: T]](s"Unknown type: $s", h))(d => DecodeResult.ok(d))

  DecodeJson[T] { c: HCursor =>
    val tf = c.downField("type")

    for {
      tv   <- tf.as[String]
      dec  <- decoder(tf.history, tv)
      data <- dec(c).map[T](identity)
    } yield data
  }
}

case class Container(id: Int, events: ContainerData)
case class ContainerData(data: List[Event])

sealed trait Event
case class Birthday(name: String, age: Int) extends Event
case class Appointment(start: Long, participants: List[String]) extends Event

implicit val eventDecoder: DecodeJson[Event] = decodeByType[Event](
  "birthday" -> DecodeJson.derive[Birthday],
  "appointment" -> DecodeJson.derive[Appointment]
)

implicit val containerDataDecoder: DecodeJson[ContainerData] = DecodeJson.derive[ContainerData]
implicit val containerDecoder: DecodeJson[Container] = DecodeJson.derive[Container]

val goodJsonStr =
  """
    {
       "id":1674,
       "events": {
          "data": [
             {
                "type": "birthday",
                "name": "Jones Clinton",
                "age": 34
             },
             {
                "type": "appointment",
                "start": 1675156665555,
                "participants": [
                   "John Doe",
                   "Jane Doe",
                   "Foo Bar"
                ]
             }
          ]
       }
    }
  """

def main(args: Array[String]) = {
  println(goodJsonStr.decode[Container])

  // \/-(Container(1674,ContainerData(List(Birthday(Jones Clinton,34), Appointment(1675156665555,List(John Doe, Jane Doe, Foo Bar))))))
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM