将特质序列化为Json

时间:2019-04-16 18:16:36

标签: scala circe argonaut

我写了一个库,用户可以在其中提供某些类字段的自定义实现。现在事实证明,我的库代码必须将这些类序列化为json,这似乎与我习惯使用circeargonaut的库无关。

这是一个简化的示例

case class LibraryObject(field: FieldOfCustomType, otherField: String)
trait FieldOfCustomType

import argonaut.Argonaut._
import argonaut.ArgonautShapeless._
// won't work, no instance of EncodeJson[FieldOfCustomType]
libraryObject.asJson.nospaces 

这对我来说非常有意义。我觉得我应该允许用户让他们定义自定义序列化器/反序列化器。但是我不知道如何使该解决方案更干净,因为我目前的方法很棘手:

// require user to include implementation on classpath
trait FieldOfCustomTypeJsonFactory {
  def toJson(obj: FieldOfCustomType): String
  def fromJson(json: String): FieldOfCustomType
}

我真的希望你们中的一些人有更好的主意。但是由于问题的运行时性质,我对此无能为力。

0 个答案:

没有答案