2015-07-11 31 views
1

我正在使用Play框架和ReactiveMongo。我正在为我的班级写一篇名为Platforms的读者和作家。我试图使用我创建的类型作为scala枚举,但我不知道应如何定义读写器语法。有人能帮我弄清楚正确的语法吗?如何将ReactiveMongo与枚举一起使用?

import reactivemongo.bson._ 

sealed trait PlatformType { def name: String } 
case object PROPER extends PlatformType { val name = "PROPER" } 
case object TRANSACT extends PlatformType { val name = "TRANSACT" } 
case object UPPER extends PlatformType { val name = "UPPPER" } 


case class Platforms(
    id: Option[BSONObjectID], 
    Platform: PlatformType, 
    Active: Boolean, 
    SystemIds:List[String], 
    creationDate: Option[DateTime], 
    updateDate: Option[DateTime]) 

object Platforms { 

implicit object PlatformsBSONReader extends BSONDocumentReader[Platforms] { 
    def read(doc: BSONDocument): Platforms = 
    Platforms(
     doc.getAs[BSONObjectID]("_id"), 
     doc.getAs[PlatformType]("Platform").get, 
     doc.getAs[Boolean]("Active").get, 
     doc.getAs[List[String]]("SystemIds").get, 
     doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)), 
     doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value))) 
} 

implicit object PlatformsBSONWriter extends BSONDocumentWriter[Platforms] { 
    def write(platforms: Platforms): BSONDocument = 
     BSONDocument(
     "_id" -> platforms.id.getOrElse(BSONObjectID.generate), 
     "Platform" -> platforms.Platform, 
     "Active" -> platforms.Active, 
     "SystemIds" -> platforms.SystemIds, 
     "creationDate" -> platforms.creationDate.map(date => BSONDateTime(date.getMillis)), 
     "updateDate" -> platforms.updateDate.map(date => BSONDateTime(date.getMillis))) 
    } 
} 
+0

没有什么特定的枚举类型提供BSON类型类。这是您可以提供'BSONWriter'和'BSONReader'的普通特质或类。 – cchantep

+0

你能告诉我你将使用的语法吗?我是scala的新手,我对如何定义枚举有点困惑。 – pitchblack408

回答

1

对于PlatformType

implicit object PTW extends BSONWriter[PlatformType, BSONString] { 
    def write(t: PlatformType): BSONString = BSONString(n.type) 
} 
implicit object PTR extends BSONReader[BSONValue, PlatformType] { 
    def read(bson: BSONValue): PlatformType = bson match { 
    case BSONString("PROPER") => PROPER 
    // ... 
    } 
} 

有关于BSON读者&作家ReactiveMongo在线documentation