0

我有系统需要将不同类型的对象序列化为 json 和 xml。其中一些是 Lift MetaRecords,一些是案例类。我想使用类型类并创建类似的东西:

trait Serializable[T] {
  serialize[T](obj: T): T
}

以及 json、xml 和 open for extension 的常用实现。

我现在面临的问题是序列化本身。目前有不同的上下文来序列化对象。想象一下新闻提要系统。共有三个对象:用户、帖子(提要元素)和照片。这些对象具有一些属性并且可以相互引用。现在,在同样的情况下,我想单独序列化对象(用户设置、首选项等),在其他情况下,我还需要序列化其他对象,即。Feed: List[Post] + 相关照片。为此,我需要提供引用的对象。

我当前的实现因可选参数函数而臃肿。

def feedAsJson(post: MPost, grp: Option[PrivateGroup], commentsBox: Option[List[MPostComment]] = Empty): JObject

我考虑过实施某种上下文解决方案。使用将提供必要数据的隐式上下文参数重载 feedAsJson。我不知道我想如何实现它,因为它可能与蛋糕模式接触数据库。任何建议都非常感谢。

4

2 回答 2

1

你不能把隐含在创建你需要的正确类型的序列化器的范围内吗?大意是这样的:

def doNothingSerializer[T]: Serializable[T] = ???
implicit def mpostToJson(implicit pgs:Serializable[PrivateGroup]], 
                                  cmts:Serializable[List[MPostComment]]) = 
  new Serializable[MPost] {
    def serialize(mpost: MPost): JObject = {
      val privateGroupJSon = pgs.serialize(mpost.privateGroup)
      // make the mpost json with privateGroupJSon which would be empty
      ???
    }
}

// later where you need to serialize without the inner content:
implicit val privateGroupToJson = doNothingSerializer[PrivateGroup]
implicit val mpostCommentsToJson = doNothingSerializer[List[MPostComment]]
implicitly[Serializable[MPost]].serialize(mpost)

您需要在随后继承的特征中定义默认的可序列化实例(以便低优先级隐式在范围内)。

请注意,我假设 Serializable 的特征是:

trait Serializable[T] {
  def serialize(t: T): JObject
}

(没有[T]方法类型参数并返回 a JObject

于 2013-08-06T06:39:46.853 回答
0

也许“Scala Pickling”可以帮助你:

http://lampwww.epfl.ch/~hmiller/pickling

我刚看了介绍。

问候保罗

于 2013-08-06T21:43:18.457 回答