我有以下 JSON 結構,但找不到在Scala 中 決議它的好方法(我正在使用circe BTW):
{
"name": "xx",
"args": [
{"name":"xy", "args": []},
[
{"name":"xy", "args": []},
{"name":"xy", "args": [[]]}
],
[
[
{"name":"xy", "args": [{"name":"xy", "args": []}]}
]
]
]
}
基本上,它是一個遞回結構,可以包含物件、物件串列、串列串列或串列串列......或物件和串列。
我該如何處理?我正在考慮一些遞回型別,但我不確定。
uj5u.com熱心網友回復:
您需要將其建模為 ADT 并派生如下自定義Decoder:
import io.circe.{Decoder, DecodingFailure, parser}
import io.circe.generic.semiauto.deriveDecoder
sealed trait Arg
object Arg {
final case class OneArg(name: String, args: List[Arg]) extends Arg
final case class MultipleArgs(args: List[Arg]) extends Arg
private implicit final val OneArgDecoder: Decoder[OneArg] = deriveDecoder
implicit final val ArgDecoer: Decoder[Arg] =
Decoder.instance[Arg] { cursor =>
cursor.focus match {
case Some(json) =>
// Here you may also ask if it is an array before to attempt to get it as a List[arg], and if not then provide a custom failure.
if (json.isObject) json.as[OneArg]
else json.as[List[Arg]].map(MultipleArgs)
case None =>
Left(DecodingFailure("Empty cursor", cursor.history))
}
}
}
可用于解碼您的 JSON:https : //scastie.scala-lang.org/BalmungSan/W0lLBYRzTIS3PC4E5i0wXA/26
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/372706.html
