Casbah从BasicDBObject到我的类型

时间:2013-12-22 22:10:08

标签: scala casbah

我在数据库中有一个如下所示的集合:

Question
    {
        "_id" : ObjectId("52b3248a43fa7cd2bc4a2d6f"),
        "id" : 1001,
        "text" : "Which is a valid java access modifier?",
        "questype" : "RADIO_BUTTON",
        "issourcecode" : true,
        "sourcecodename" : "sampleques",
        "examId" : 1000,
        "answers" : [ 
            {
                "id" : 1,
                "text" : "private",
                "isCorrectAnswer" : true
            }, 
            {
                "id" : 2,
                "text" : "personal",
                "isCorrectAnswer" : false
            }, 
            {
                "id" : 3,
                "text" : "protect",
                "isCorrectAnswer" : false
            }, 
            {
                "id" : 4,
                "text" : "publicize",
                "isCorrectAnswer" : false
            }
        ]
    }

我有一个表示问题和答案的案例类。问题案例类有一个Answer对象列表。我尝试转换查找操作的结果,将DBObject转换为我的答案类型:

  def toList[T](dbObj: DBObject, key: String): List[T] =
    (List[T]() ++ dbObject(key).asInstanceOf[BasicDBList]) map { _.asInstanceOf[T]}

当我将其称为

时,上述操作的结果
toList[Answer](dbObj, "answers") map {y => Answer(y.id,y.text, y.isCorrectAnswer)}

失败,出现以下异常:

com.mongodb.BasicDBObject cannot be cast to domain.content.Answer

为什么会失败?有没有办法将DBObject转换为我想要的Answer类型?

1 个答案:

答案 0 :(得分:2)

您必须从BasicDBObject中检索值,强制转换它们然后填充Answer类:

答案课:

 case class Answer(id:Int,text:String,isCorrectAnswer:Boolean)

toList,我把它改成了返回List [Answer]

 def toList(dbObj: DBObject, key: String): List[Answer] = dbObj.get(key).asInstanceOf[BasicDBList].map { o=>
    Answer(
     o.asInstanceOf[BasicDBObject].as[Int]("id"),
     o.asInstanceOf[BasicDBObject].as[String]("text"),
     o.asInstanceOf[BasicDBObject].as[Boolean]("isCorrectAnswer")
    )
  }.toList