如何将 Scala 对象序列化为 Json 其中已经包含一些 Json

How to serialize a Scala object to Json which already contains some Json

我有以下对象,我正在使用 Circe

将其序列化为 json
case class Person(name: String, data: String)
val x = Person("test", s"""{"a": 10, "b":"foo"}""")
import io.circe._, io.circe.generic.auto._, io.circe.parser._, io.circe.syntax._
println(x.asJson)

上面语句的输出是

{
  "name" : "test",
  "data" : "{\"a\":10, \"b\":\"foo\"}"
}

但我想要的输出是

{
    "name": "test",
    "data": {
        "a": 10,
        "b": "foo"
    }
}

我从基于 json 的数据存储中获取数据字段的数据。我想通过它(所以我不想将它解组为 scala 对象,只是为了再次将它解组为 json。marshall/demarshall 是对我的 CPU 的浪费服务器。

那么我该如何处理这些数据呢?

好吧,您可以编写自己的 Encoder 实现,例如:

import io.circe.{Encoder, Json}
import io.circe.jawn.parse

case class Person(name: String, data: String)

implicit val personEncoder: Encoder[Person] = new Encoder[Person] {
  override def apply(person: Person): Json = {
    val name = Json.fromString(person.name)
    val data = parse(person.data) match {
      case Left(_)      => Json.obj()
      case Right(value) => value
    }
    Json.obj("name" -> name, "data" -> data)
  }
}

事实上,您的情况很不寻常 - 其中一个字段是 String,在将其作为子 Json 节点之前,您需要对其进行解析。需要以某种方式处理错误失败 - 我使用了空对象,但这不一定是你想要使用的。

如果您想省略反序列化步骤...那是不可能的。您正在构建具有定义行为的 JSON 个节点的树。 String 不能突然被当作 Json object.