简体   繁体   English

JSON4S 无法反序列化对象

[英]JSON4S not able to deserialize object

I have one class which extends a trait as shown below:我有一个类,它扩展了一个特性,如下所示:

case class Phone(number: String)

trait Person {
  def name: String
  def phones: Seq[Phone]
}

case class Employee(name: String, phones: Seq[Phone] = Seq.empty) extends Person

As shown above, Employee class extends Person trait.如上所示, Employee类扩展了Person trait。

I am trying to serialize and then deserialize one object of type Employee as shown below:我正在尝试序列化然后反序列化Employee类型的一个对象,如下所示:

implicit val formats = DefaultFormats

val emp: Person = Employee("foo")
val c = write(emp)
val e2 = parse(c).extract[Person]

Object emp gets serialized properly对象emp被正确序列化

emp: Person = Employee(foo,List())
c: String = {"name":"foo","phones":[]}

but parse(c).extract[Person] method fails with following exception:parse(c).extract[Person]方法失败并出现以下异常:

org.json4s.package$MappingException: No constructor for type Person, 
JObject(List((name,JString(foo)), (phones,JArray(List()))))

I tried to add FieldSerializer like below but got same exception.我尝试添加如下所示的FieldSerializer ,但遇到了同样的异常。

implicit val formats = DefaultFormats + FieldSerializer[Employee with Person]()

So I started writing custom serializer which looks like below:所以我开始编写自定义序列化程序,如下所示:

case object PersonSerializer extends CustomSerializer[Person](formats => (
  {
    case JObject(
      List(
        JField("name", JString(name)),
        JField("phones", JArray(List(phones)) )
      )
    ) => Employee(name, phones)
  },
  {
    case Employee(name, phones) => JObject(JField("name", JString(name)))
  }
))

but this serializer fails to compile with following error:但此序列化程序无法编译并出现以下错误:

type mismatch;
found   : org.json4s.JsonAST.JValue
required: Seq[Phone]
) => Employee(name, phones)

So can you please help me with either writing custom serializer or to convert JValue to Seq[Phone] ?那么您能帮我编写自定义序列化程序或将JValue转换为Seq[Phone]吗?

I don't think your actual problem is the one you think it is--you can't extract a Person, it's a trait!我不认为你的实际问题是你认为的那个——你不能提取一个人,这是一种特质! I'd extract an Employee, instead;相反,我会提取一个员工; if you need it to be a Person, just cast it to a Person after extraction.如果你需要它是一个人,只需在提取后将其转换为一个人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM