【问题标题】:How to convert casbah mongodb list to json in scala / play如何在scala / play中将casbah mongodb列表转换为json
【发布时间】:2012-08-12 19:07:50
【问题描述】:

我目前正在学习scala和mongodb,正在使用该剧!框架,所以我在思考问题时犯了各种各样的错误。目前我有一个 scala 对象,它通过 casbah 返回从 mongodb 查询返回的数据库对象列表,如下所示;

object Alerts  {

   def list() : List[DBObject]= {

        val collection = MongoDatabase.collection;
        val query = MongoDBObject.empty
        val order = MongoDBObject("Issue Time:" -> -1)
        val list = collection.find(query).sort(order).toList
        list
   }

... }

在我的代码的其他地方,我希望在 Json 中输出对象列表 - 所以我有;

  val currentAlerts = Alerts.list()

我想写的是类似的东西;

  val resultingJson = currentAlerts.toJson 

但是当我这样做时,我会得到以下错误,这是可以理解的;

  value toJson is not a member of List[com.mongodb.casbah.Imports.DBObject]

我的问题是 - 将 com.mongodb.casbah.Imports.DBObject 列表转换为 Json 以进行输出的正确方法是什么?

编辑:

为了清楚起见,我真正想做的是相当于

val listInJson = collection.find(query).sort(order).toJson

就像我能写的一样

val listAsString = collection.find(query).sort(order).toString

【问题讨论】:

  • 你试过Json.toJson()函数了吗? (playframework.org/documentation/2.0.2/ScalaJson)
  • 那么为什么你真的需要将数据转换为 json ?它在 db 中存储为 json(真的是 bson),你真的需要同样的备份吗?我认为您可能只想根据所需的结构将数据复制到对象中,然后将其序列化为 json...
  • 我需要将其输出为 JSON 以供 Web 服务使用。
  • 你见过api.mongodb.org/java/current/com/mongodb/util/… 吗?我想知道这是否对你有用......
  • @Roger,你找到优雅的解决方案了吗?

标签: scala mongodb playframework casbah


【解决方案1】:

你可以试试

com.mongodb.util.JSON.serialize(Alerts.list())

这应该返回一个带有警报的 JSON 数组

【讨论】:

    【解决方案2】:

    我有以下

    def service() = Action {
     // connect
     val collection = MongoConnection()("someDB")("someCollection")
     // simply convert the result to a string, separating items with a comma
     // this string goes inside an "array", and it's ready to hit the road
     val json = "[%s]".format(
      collection.find(someQuery).toList.mkString(",")
     )
    
     Ok(json).as("application/json")
    

    }

    【讨论】:

      【解决方案3】:

      我有一个可怕的解决方案如下;

      val currentAlerts = Alerts.list()
      
      var jsonList : List[JsValue] = Nil
      
      // Iterate over the DBObjects and use to String to convert each to JSON
      // and then parse that back into the list so we can use toJson on it later.
      // MAD, but works.
      
      for (dbObject <- currentAlerts) {
          jsonList ::=  Json.parse(dbObject.toString)
      }
      
      val result = Json.toJson(jsonList)
      Ok(result).as("application/json")
      

      肯定有更好的方法吗?

      【讨论】:

      • 嘿,Roger,你有没有找到更好的方法将 casbah DBObject 转换为 play 的 JsValue?
      • 得到result后,如何将其key-value字段填充到map中?
      • 这实际上是一个绝妙的主意!如果性能无关紧要(例如,在漂亮的打印中不重要),这是完美的。谢谢。
      猜你喜欢
      • 2013-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多