我有以下代码段:
val serializedClasses: List[MongoMetaRecord[MongoRecord[_]]] = List(User, Email)
不幸的是,我无法从元素中获取确切的类型信息,并且以下代码失败:
serializedClasses.map(c => new RecordSerializer(c))
[error] JsonFormats.scala:19: inferred type arguments [_$1] do not conform to class RecordSerializer's type parameter bounds [T <: net.liftweb.mongodb.record.MongoRecord[T]]
[error] implicit val jsonformats = DefaultFormats + (new ObjectIdSerializer) + (new RecordSerializer(DirectMessage)) + (new RecordSerializer(User)) ++ serializedClasses.map(c => new RecordSerializer(c))
以下是RecordSerializer.scala
object RecordSerializer {
def apply[T <: MongoRecord[T]](meta: MongoMetaRecord[T]) = new RecordSerializer(meta)
}
class RecordSerializer[T <: MongoRecord[T]](meta: MongoMetaRecord[T]) extends Serializer[MongoRecord[T]] {
def deserialize(implicit format: Formats): PartialFunction[(TypeInfo, JValue), MongoRecord[T]] = {
case (TypeInfo(clazz, parametrizedType), json: JValue) if(JsonFormats.serializedClassesNames.contains(clazz.getSimpleName)) => {
meta.fromJValue(json).openOr(throw new MappingException("Couldn't convert"))
}
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case rec: MongoRecord[_] => rec.asJValue
}
}
答案 0 :(得分:1)
我不清楚这里的问题是什么。如何编译? RecordSerializer采用类型化的MongoRecord,而List不捕获其项目的类型。如果你想让它工作,你需要捕获记录类型(你可以使用像Shapeless提供的HList来捕获每个项目的类型)或者你需要重写你的RecordSerializer以便它只在运行时从记录中获取它的类型信息,而不依赖于知道编译时类型。