sách gpt4 ai đã đi

Chơi Json Đọc Json lồng nhau chung chung được tuần tự hóa

In lại 作者:行者123 更新时间:2023-12-04 10:34:22 26 4
mua khóa gpt4 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])
}

1 Câu trả lời

您只需添加 mapOuter.reads施工后validate[T]Gọi.

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

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
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com