我怎样才能从中得到List(String)
一个MongoDBList
?
val a: MongoDBList = ... // equal to [ { "id" : "0001"} , { "id" : "0017"}]
期望的结果:List("0001", "0017")
MongoDBList扩展了scala.collection.mutable.LinearSeq所以你应该能够使用 toList
val bld = MongoDBList.newBuilder
bld += MongoDBObject("id" -> "0001")
bld += MongoDBObject("id" -> "0017")
val a = bld.result
val l = for( o <- a.toList )
yield JSON.parse(o.toString).asInstanceOf[DBObject].get("id")
println(l)
//output
//List(0001, 0017)
我会比较喜欢:
val bld = MongoDBList.newBuilder
bld += MongoDBObject("id" -> "0001")
bld += MongoDBObject("id" -> "0017")
val a = bld.result
a.map(x=> x.asInstanceOf[DBObject].getAs[String]("id").get)
// or to avoid nonexitence emelents
a.flatMap(x=> x.asInstanceOf[DBObject].getAs[String]("id"))
我不喜欢这里的 asInstanceOf 如果你有
{ "data" : [ { "id" : "0001"} , { "id" : "0017"}] }
casbash 可以为你序列化 Seq
val a2 = MongoDBObject( "data" -> a )
a2.getAs[Seq[DBObject]]("aa").get.map { x => x.getAs[String]("id").get}