gpt4 book ai didi

scala - 如何使用 jsonspray 序列化具有特征的案例类

转载 作者:行者123 更新时间:2023-12-02 07:42:04 26 4
gpt4 key购买 nike

我明白如果我有:

case class Person(name: String)

我可以使用

object PersonJsonImplicits extends DefaultJsonProtocol {
implicit val impPerson = jsonFormat1(Person)
}

因此将其序列化为:

import com.example.PersonJsonImplicits._
import spray.json._
new Person("somename").toJson

但是如果我有呢

trait Animal
case class Person(name: String) extends Animal

我的代码中有某个地方

val animal = ???

我需要序列化它并且我想使用 json Spray

我应该添加哪个序列化器我希望有类似的东西:

object AnimalJsonImplicits extends DefaultJsonProtocol {
implicit val impAnimal = jsonFormat???(Animal)
}

也许我需要添加一些匹配器来检查动物是什么类型,这样如果它是一个人,我会将其定向到人,但什么也没发现......正在阅读 https://github.com/spray/spray-json并且不明白该怎么做..

那么我如何序列化该组

trait Animal
case class Person(name: String) extends Animal

用json喷雾?

最佳答案

您有几个选择:

选项 1

扩展RootJsonFormat[Animal]并放置您的自定义逻辑以匹配不同类型的Animal:

import spray.json._
import DefaultJsonProtocol._

trait Animal
case class Person(name: String, kind: String = "person") extends Animal

implicit val personFormat = jsonFormat2(Person.apply)
implicit object AnimalJsonFormat extends RootJsonFormat[Animal] {
def write(a: Animal) = a match {
case p: Person => p.toJson
}
def read(value: JsValue) =
// If you need to read, you will need something in the
// JSON that will tell you which subclass to use
value.asJsObject.fields("kind") match {
case JsString("person") => value.convertTo[Person]
}
}

val a: Animal = Person("Bob")
val j = a.toJson
val a2 = j.convertTo[Animal]

如果将此代码粘贴到 Scala REPL 中,您将得到以下输出:

a: Animal = Person(Bob,person)
j: spray.json.JsValue = {"name":"Bob","kind":"person"}
a2: Animal = Person(Bob,person)

Source

选项 2

另一种选择是为 PersonAnimal 的任何其他子类提供隐式 jsonFormat,然后编写序列化代码,如下所示:

def write(a: Animal) = a match {
case p: Person => p.toJson
case c: Cat => c.toJson
case d: Dog => d.toJson
}

Source

关于scala - 如何使用 jsonspray 序列化具有特征的案例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20946701/

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