如何在Scala中使用Json4s序列化密封的抽象类?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Scala中使用Json4s序列化密封的抽象类?相关的知识,希望对你有一定的参考价值。

如何在Scala中使用Json4s序列化密封的抽象类?

定义了以下类:

sealed abstract class Person extends Product with Serializable
case class Spouse(name: String, age: Int) extends Person
case class Customer(name: String, age: Int, spouse: Spouse) extends Person

我创建了一个Customer类型的对象:

val customer: Customer = Customer("Joe", 35, Spouse("Marilyn", 33))

然后我序列化为JSON:

implicit val formats = DefaultFormats
val serialized = write(customer)

这很好。但后来我尝试反序列化:

val parsedObj = Serialization.read[Person](serialized)

在这里,我不断收到错误:

org.json4s.package $ MappingException:解析的JSON值与类构造函数不匹配

我花了很多时间试图做这项工作......

答案

经过大量的谷歌搜索和仔细阅读Json4s文档后,我发现我需要一个自定义的串行器来使其工作。

然而,我花了一段时间才发现I need to set the formats实际上使用了自定义的Serializer。

这是适合我的代码。

简单示例:

import org.json4s._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization.{read, write}
import org.json4s.native.Serialization

sealed abstract class Person extends Product with Serializable
case class Spouse(name: String, age: Int) extends Person
case class Customer(name: String, age: Int, spouse: Spouse) extends Person

val customer: Customer = Customer("Joe", 35, Spouse("Marilyn", 33))

implicit val formats = Serialization.formats(NoTypeHints) + PersonSerializer
val serialized = write(customer)    
val parsedObj = Serialization.read[Person](serialized)

自定义序列化器:

object PersonSerializer extends Serializer[Person] {
    private val PersonClass = classOf[Person]

    def deserialize(implicit format: Formats)
    : PartialFunction[(TypeInfo, JValue), Person] = {
        case (TypeInfo(PersonClass, _), json) =>
            json match {
                case JObject(List(
                    JField("name", JString(d)),
                    JField("age", JInt(f)),
                    ("spouse", JObject(List(JField("name", JString(g)), JField("age", JInt(h)))))
                    )) => Customer(d, f.toInt, Spouse(g, h.toInt))
                case JObject(List(
                    JField("name", JString(d)),
                    JField("age", JInt(f))
                    )) => Spouse(d, f.toInt)
            }
    }

    def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
        case x: Customer =>
            JObject(List(
                JField("name", JString(x.name)),
                JField("age", JInt(x.age)),
                ("spouse", JObject(List(JField("name", JString(x.spouse.name)), JField("age", JInt(x.spouse.age)))))
            ))
        case x: Spouse =>
            JObject(List(
                JField("name", JString(x.name)),
                JField("age", JInt(x.age))
            ))
    }
}

产量

scala> val serialized = write(customer)

serialized:String = {“name”:“Joe”,“age”:35,“spouse”:{“name”:“Marilyn”,“age”:33}}

scala> val parsedObj = Serialization.readPerson

parsedObj:Person = Customer(Joe,35,Spouse(Marilyn,33))

以上是关于如何在Scala中使用Json4s序列化密封的抽象类?的主要内容,如果未能解决你的问题,请参考以下文章

Scala的密封抽象与抽象类

在 json4s 中自定义CustomSerializer

找不到类的 ScalaSig - json4s with scala + proguard for an android app

如何使用带有 UTF-8 字符的 json4s 序列化 JSON?

scala - fold,aggregate,iterator

求助:scala的json4s把JValue转为对象时报错 java.lang.NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$l