我写了一个库,用户可以在其中提供某些类字段的自定义实现。现在事实证明,我的库代码必须将这些类序列化为json,这似乎与我习惯使用circe
或argonaut
的库无关。
这是一个简化的示例
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
}
我真的希望你们中的一些人有更好的主意。但是由于问题的运行时性质,我对此无能为力。