使用 lift-json 将 MongoDB ObjectID 作为 JSON

发布于 2024-12-22 18:07:13 字数 1106 浏览 1 评论 0原文

我正在为一些 REST API 使用 Bowler 框架(内部使用 lift-json 模块进行繁重的工作),并有以下情况类:

case class Item(_id : ObjectId, name : String, value : String)

当我将此案例对象返回给客户端时,我需要包含 _id 字段的值。但是,_id 列在 Json 输出中作为空列表返回,而不是其实际值。

{"_id":{},"name":"Id Test","value":"id test"}

任何有关如何解决此问题的指示将不胜感激。

更新:我尝试使用自定义序列化器,但由于某种原因它没有被调用!

    class ObjectIdSerializer extends Serializer[ObjectId] {
    private val Class = classOf[ObjectId]

    def deserialize(implicit format: Formats) = {
      case (TypeInfo(Class, _), json) => json match {
        case JObject(JField("_id", JString(s)) :: Nil) => new ObjectId(s)
        case x => throw new MappingException("Can't convert " + x + " to  ObjectId")
      }
    }

    def serialize(implicit format: Formats) = {
      case x: ObjectId => { println("\t @@@@@@@@Custom Serializer was called!"); JObject(JField("_id", JString(x.toString)) :: Nil)}
    }
  }

  implicit val formats = DefaultFormats + new ObjectIdSerializer

I'm using Bowler framework for some REST API's (internally uses lift-json module for heavy lifting) and have the following case class:

case class Item(_id : ObjectId, name : String, value : String)

When I return this case object back to client I need to include value for _id field. However, the _id column is being returned as an empty list in Json output instead of its actual value.

{"_id":{},"name":"Id Test","value":"id test"}

Any pointers on how this can be fixed will be greatly appreciated.

Update: I tried using custom serializer for it but for some reason it doesn't get called!

    class ObjectIdSerializer extends Serializer[ObjectId] {
    private val Class = classOf[ObjectId]

    def deserialize(implicit format: Formats) = {
      case (TypeInfo(Class, _), json) => json match {
        case JObject(JField("_id", JString(s)) :: Nil) => new ObjectId(s)
        case x => throw new MappingException("Can't convert " + x + " to  ObjectId")
      }
    }

    def serialize(implicit format: Formats) = {
      case x: ObjectId => { println("\t @@@@@@@@Custom Serializer was called!"); JObject(JField("_id", JString(x.toString)) :: Nil)}
    }
  }

  implicit val formats = DefaultFormats + new ObjectIdSerializer

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

顾忌 2024-12-29 18:07:13

这是固定的。需要定义我自己的 RenderStrategy 类才能覆盖格式声明。这篇文章有更多详细信息 http://blog.recursivity.com/post/5433171352/how-bowler-does-rendering-maps-requests-to-objects

This is fixed. Needed to define my own RenderStrategy class in order to override the formats declaration. This post has more details on it http://blog.recursivity.com/post/5433171352/how-bowler-does-rendering-maps-requests-to-objects

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文