如何在scala/play中将casbah mongodb列表转换为json [英] How to convert casbah mongodb list to json in scala / play

查看:107
本文介绍了如何在scala/play中将casbah mongodb列表转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习scala和mongodb并使用该剧本!框架,所以我在处理问题时会犯各种错误.当前,我有一个scala对象,该对象返回通过casbah从mongodb查询返回的数据库对象的列表,如下所示;

I'm learning scala and mongodb at present and using the play! framework, so I'm making all sorts of mistakes as I get my head around things. Currently I have a scala object that returns a list of database objects returned from a mongodb query via casbah as follows;

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中输出对象列表-这样,我就可以了;

Elsewhere in my code I wish to output the List of objects in Json - so I have;

  val currentAlerts = Alerts.list()

我想写的东西是这样的

  val resultingJson = currentAlerts.toJson 

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

But when I do this, I understandably get the following error;

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

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

My question is - what's the right way to convert a List of com.mongodb.casbah.Imports.DBObject into Json for output?

为清楚起见,我真正想做的就是

For clarity, what I really want to do is the equivalent of

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

以我可以写的相同方式

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

推荐答案

您可以尝试

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

这应该返回包含警报的JSON数组

This should return a JSON array with your Alerts

这篇关于如何在scala/play中将casbah mongodb列表转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆