How to convert casbah mongodb list to json in scala / play

前端 未结 3 351
余生分开走
余生分开走 2020-12-16 01:31

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 objec

相关标签:
3条回答
  • 2020-12-16 02:12

    I have the following

    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")
    

    }

    0 讨论(0)
  • 2020-12-16 02:18

    You can try

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

    This should return a JSON array with your Alerts

    0 讨论(0)
  • 2020-12-16 02:18

    I have what is a horrid solution as follows;

    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")
    

    There must surely be a better way?

    0 讨论(0)
提交回复
热议问题