简体   繁体   English

如何在Scala中解析此“漂亮”的BSON?

[英]How to parse this “pretty” BSON in Scala?

In our project we are using Scala and Reactivemongo. 在我们的项目中,我们使用Scala和Reactivemongo。 (I'm very new to both) When you print to the console a "pretty" Bson, it looks like this: (我都是新手)当您在控制台上打印“漂亮”的Bson时,它看起来像这样:

{  _id: BSONObjectID("52b006fe0100000100d47242"),
desc: BSONString({"_id:"BSONObjectID(52af03a5010000010036194d),"desc:"BSONString(www.foo.com"hits),"domains:"["0:"BSONString(www.foo.com)"],"func:"BSONString(Count),"maxr:"BSONInteger(5),"props:"["]"} hits),
domains: [
0: BSONString(jsonString)
],
func: BSONString(Count),
maxr: BSONInteger(5),
props: [
]
}

I need to be able to parse it back from the console into a corosponding Case Class. 我需要能够将其从控制台解析回对应的Case类。

Any help please? 有什么帮助吗?

taken from typesafe's activator template, you can simply use Json.format as an implicit val in the case class's companion object (ReactiveMongo 0.9, scala 2.10.2). 取自typesafe的激活器模板,您可以简单地将Json.format用作case类的伴随对象(ReactiveMongo 0.9,scala 2.10.2)中的隐式val。 example: 例:

package models

import play.api.libs.json.Json
import reactivemongo.bson.BSONObjectID
import play.modules.reactivemongo.json.BSONFormats._

/**
 * A message class
 *
 * @param _id The BSON object id of the message
 * @param message The message
 */
case class Message(_id: BSONObjectID, message: String)

object Message {
  /**
   * Format for the message.
   *
   * Used both by JSON library and reactive mongo to serialise/deserialise a message.
   */
  implicit val messageFormat = Json.format[Message]
}

i am using it, and you can use more parameters as long as JSON knows how to format them, or, if you have members that are case classes you created, if the have the same: 我正在使用它,并且只要JSON知道如何格式化它们,您就可以使用更多参数,或者,如果您拥有的是创建的案例类成员,则可以使用更多参数:

package models

import play.api.libs.json.Json
import reactivemongo.bson.BSONObjectID
import play.modules.reactivemongo.json.BSONFormats._

/**
 * A message class
 *
 * @param _id The BSON object id of the message
 * @param message The message
 */

case class Name(fName: String, lName: String, mInitial: String)

object Name {
  implicit val nameFormat = Json.format[Name]
}

case class Message(_id: BSONObjectID, message: String, name: Name)

object Message {
  /**
   * Format for the message.
   *
   * Used both by JSON library and reactive mongo to serialise/deserialise a message.
   */
  implicit val messageFormat = Json.format[Message]
}

i still have not figured a way to do it if you have auxiliary constructors, or if you implement apply(...) in the companion. 如果您有辅助构造函数,或者在同伴中实现apply(...),我仍然没有想办法。 however, the compiler will alert you to that. 但是,编译器会提醒您。

You can check how they did it at this link in Reactivemongo documentation: http://stephane.godbillon.com/2012/10/18/writing-a-simple-app-with-reactivemongo-and-play-framework-pt-1.html 您可以在Reactivemongo文档中的此链接中查看他们的操作方式: http//stephane.godbillon.com/2012/10/18/writing-a-simple-app-with-reactivemongo-and-play-framework-pt- 1.html

implicit object ArticleBSONReader extends BSONReader[Article] {
def fromBSON(document: BSONDocument) :Article = {
  val doc = document.toTraversable
  Article(
    doc.getAs[BSONObjectID]("_id"),
    doc.getAs[BSONString]("title").get.value,
    doc.getAs[BSONString]("content").get.value,
    doc.getAs[BSONString]("publisher").get.value,
    doc.getAs[BSONDateTime]("creationDate").map(dt => new DateTime(dt.value)),
    doc.getAs[BSONDateTime]("updateDate").map(dt => new DateTime(dt.value)))
  }
}

Here a solution I'm using. 这是我正在使用的解决方案。 I hope it helps -> 希望对您有所帮助->

    def bsonToString(bson: BSONDocument): String = {
        val bsonAsKeyValueList = bson.toMap.toList.map {
          case (key, document: BSONDocument) =>
            (key, bsonToString(document))
          case (key, value: BSONValue) =>
            (key, value.toString)
        }
        val bsonAsKeyValueStrings = bsonAsKeyValueList.map {
          case (key, value) =>
            s"""("${key}" -> ${value})"""
        }
        bsonAsKeyValueStrings.mkString("BSONDocument", ", ", "")
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM