Serialization and Deserialization of Subclasses with spray-json

509 views Asked by At

assume I have one base class B and two subclasses S1 and S2.

I want serialize and deserialize class S1 and S2.

Therefore I have two questions:

  1. Is it possible two write a JsonFormat for class B and use it in class S1 and S2 for serialization?

  2. I want two deserialize class S1 and S2. But I do not know if the json String represents class S1 or S2, so I think I can not use spray-json method convertTo because I have to know the exact type I want to deserialize.

My solution to 2. would be to write a wrapper class which contains the a string for the type (S1 or S2) and the json String for S1 or S2. Is this the best way two go or are there other better ways to do it?

Thanks in advance

1

There are 1 answers

3
lmm On BEST ANSWER

It's possible but your format won't (and can't) serialize any details of S1 or S2 that aren't part of B.

I'd suggest having separate formats for S1 and S2 and then a custom format for B that delegates to the appropriate format:

implicit val s1Format = jsonFormat3(S1) //assuming S1 and S2 are case classes
implicit val s2Format = jsonFormat5(S2) //with 3 and 5 parameters respectively
implicit object bFormat extends RootJsonFormat[B] {
  //assuming both objects have a field called "myTypeField"
  def read(jv: JsValue) = jv.asJsObject.fields("myTypeField") match {
      case JsString("s1") => jv.convertTo[S1]
      case JsString("s2") => jv.convertTo[S2]
    }
  def write(b: B) = b match {
    case s1: S1 => s1Format.write(s1)
    case s2: S2 => s2Format.write(s2)
  }
}