gpt4 book ai didi

json - Play Json 读取嵌套泛型序列化 Json

转载 作者:行者123 更新时间:2023-12-04 10:34:22 26 4
gpt4 key购买 nike

考虑以下 JSON

{
"a": "{\"b\": 12, \"c\": \"test\"}"
}

我想定义一个泛型读取 Reads[Outer[T]]对于这种序列化的 Json
import play.api.libs.json.{Json, Reads, __}

final case class Outer[T](inner: T)
final case class SpecializedInner(b: Int, c: String)

object SpecializedInner {
implicit val reads: Reads[SpecializedInner] = Json.reads[SpecializedInner]
}

object Outer {
implicit def reads[T](implicit readsT: Reads[T]): Reads[Outer[T]] = ???
}

我怎样才能实现我的目标?我试图对字段“outer.a”进行 flatMap 字符串读取,但由于无法从经过验证的 JSON 生成 Reads[T] 而卡住了
object Outer {
implicit def reads[T](implicit readsT: Reads[T]): Reads[Outer[T]] =
(__ \ "a").read[String].flatMap(x => Json.parse(x).validate[T])
}

最佳答案

您只需添加 mapOuter.reads施工后validate[T]调用。

请参阅下一个代码,例如:

object App {

final case class Outer[T](inner: T)

object Outer {
implicit def reads[T](implicit innerReads: Reads[T]): Reads[Outer[T]] = { json: JsValue =>
json.validate[String].flatMap(string => Json.parse(string).validate[T].map(Outer.apply[T]))
}
}

final case class Root[T](a: Outer[T])
object Root {
implicit def reads[T](implicit innerReads: Reads[T]): Reads[Root[T]] = Json.reads
}

final case class SpecializedInner(b: Int, c: String)

object SpecializedInner {
implicit val reads: Reads[SpecializedInner] = Json.reads
}

def main(args: Array[String]): Unit = {
val rawJson = "{\"a\": \"{\\\"b\\\": 12, \\\"c\\\": \\\"test\\\"}\"}"
println(Json.parse(rawJson).validate[Root[SpecializedInner]])
}
}

在我的情况下产生了下一个结果:
JsSuccess(Root(Outer(SpecializedInner(12,test))),)

希望这可以帮助!

关于json - Play Json 读取嵌套泛型序列化 Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60259011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com