简体   繁体   English

用spray-json对子类进行序列化和反序列化

[英]Serialization and Deserialization of Subclasses with spray-json

assume I have one base class B and two subclasses S1 and S2. 假设我有一个基类B和两个子类S1和S2。

I want serialize and deserialize class S1 and S2. 我想序列化和反序列化类S1和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? 是否可以两个为类B写一个JsonFormat并在类S1和S2中使用它进行序列化?

  2. I want two deserialize class S1 and S2. 我想要两个反序列化类S1和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. 但是我不知道json字符串是否表示类S1或S2,所以我想我不能使用spray-json方法convertTo,因为我必须知道我要反序列化的确切类型。

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. 我对2.的解决方案是编写一个包装器类,其中包含类型(S1或S2)的字符串和S1或S2的json字符串。 Is this the best way two go or are there other better ways to do it? 这是两个人走的最好方法,还是还有其他更好的方法呢?

Thanks in advance 提前致谢

It's possible but your format won't (and can't) serialize any details of S1 or S2 that aren't part of B . 有可能,但是您的格式不会(也不能)序列化不属于BS1S2任何细节。

I'd suggest having separate formats for S1 and S2 and then a custom format for B that delegates to the appropriate format: 我建议为S1S2使用单独的格式,然后为B一个自定义格式,以委托给适当的格式:

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)
  }
}

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

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