如何序列化泛型类?

时间:2016-05-06 23:49:54

标签: scala serialization slick json4s

我有以下案例类

void dispatch_with_cancellation(void (^block)(), BOOL* cancellation) {
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC);
    dispatch_after(time, dispatch_get_main_queue(), ^{
        if (!*cancellation) {
            block();
        }
    });
}

int main(int argc, char *argv[]) {
    @autoreleasepool {
        void (^block)() = ^{
            NSLog(@"%@", @"inside block");
        };
        BOOL cancellation;
        dispatch_with_cancellation(block, &cancellation);
        // cancel the block by setting the BOOL to YES.
        *&cancellation = YES;
        [[NSRunLoop currentRunLoop] run];
    }
}

case class UserId(value: String) extends MappedTo[String] MappedTo的通用id案例类 我在json4s中声明了它的序列化器

slick.typesafe

问题是我有超过20个id字段,我不想为每个字段声明序列化程序。有没有办法为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 })) 执行此操作,以便它可以应用于其所有子类?

1 个答案:

答案 0 :(得分:0)

除非我误解了某些内容,否则根本不需要定义自己的序列化程序; case类有一个由编译器为它们定义的简单序列化方法,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]。更好的解决方案是停止使用这么多案例类,但也许这不适合您。耸肩。

相关问题