【问题标题】:How to serialized generic class?如何序列化泛型类?
【发布时间】:2016-09-02 03:37:33
【问题描述】:

我有以下案例类

case class UserId(value: String) extends MappedTo[String]

(MappedToslick.typesafe的通用id case类) 我在 json4s 中声明了它的序列化器

case object IdSerializer extends CustomSerializer[UserId](format => ( {
    case JString(s) => UserId(s)
    case JNull | JNothing => null
  }, {
    case i: UserId => JString(i.value)
    case JNull | JNothing => null
  }))

问题是我有超过 20 个这样的 id 字段,我不想为每个字段声明序列化程序。有没有办法为MappedTo 做它,以便它可以应用于它的所有子类?

【问题讨论】:

    标签: scala serialization slick json4s


    【解决方案1】:

    除非我误解了某些东西,否则您根本不需要定义自己的序列化器;案例类有一个由编译器为它们定义的简单序列化方法,以及Json4s will use that。如果您的其他 ID 字段是案例类的成员,则它们也不需要。

    编辑:

    我明白了。我不愿意提出这个建议,因为它只是修补真正的问题,即您使用的大量案例类,但这样的事情可能会起作用:

    class IdSerializer[T] extends CustomSerializer[T <: MappedTo](format => ( {
        case JString(s) => new T(s)
        case JNull | JNothing => null
      }, {
        case i: T => JString(i.value)
        case JNull | JNothing => null
      }))
    

    所以对于 UserID,您可以调用 IdSerializer[UserID]。更好的解决方案是停止使用如此多的案例类,但也许这不是您的选择。耸耸肩。

    【讨论】:

    • 是的 json4s 可以序列化大部分案例类。但是,对于UserId(value:String),它的序列化是{userId:{value:....}},这不是我所期望的。所以我创建了一个自定义序列化,使它像{userId:...}
    • 哦,我明白你为什么要这么做了。我会更新我的答案。
    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 2014-12-20
    • 2021-02-06
    • 2023-03-03
    相关资源
    最近更新 更多