加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:21:12 所属栏目:安全 来源:网络整理
导读:我明白如果我有: case class Person(name: String) 我可以用 object PersonJsonImplicits extends DefaultJsonProtocol { implicit val impPerson = jsonFormat1(Person)} 并因此序列化: import com.example.PersonJsonImplicits._import spray.json._new
我明白如果我有:

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喷雾

我应该添加哪个序列化程序我希望有一些像:

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 [动物]并放置您的自定义逻辑来匹配不同类型的动物:

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

另一个选择是为Person和Animal的任何其他子类提供隐含的jsonFormats,然后编写如下所示的序列号:

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

Source

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读