使用 lift-json 将 MongoDB ObjectID 作为 JSON
我正在为一些 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是固定的。需要定义我自己的 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