我经常不得不对求和类型(例如Either[S,T]
)进行序列化/反序列化,而且我还没有找到一种通用的方法。这是一个示例类型(基本上等同于Either
)
sealed trait OutcomeType
case class NumericOutcome(units: String) extends OutcomeType
case class QualitativeOutcome(outcomes: List[String]) extends OutcomeType
这是我对实现序列化的伴随对象的最大努力。它可以工作,但是为每种求和类型一遍又一遍地写这些事情是很累的。有什么建议可以使其变得更好和/或更通用吗?
import play.api.libs.json._
import play.api.libs.functional.syntax._
object OutcomeType {
val fmtNumeric = Json.format[NumericOutcome]
val fmtQualitative = Json.format[QualitativeOutcome]
implicit object FormatOutcomeType extends Format[OutcomeType] {
def writes(o: OutcomeType) = o match {
case n@NumericOutcome(_) => Json.obj("NumericOutcome" -> Json.toJson(n)(fmtNumeric))
case q@QualitativeOutcome(_) => Json.obj("QualitativeOutcome" -> Json.toJson(q)(fmtQualitative))
}
def reads(json: JsValue) = (
Json.fromJson(json \ "NumericOutcome")(fmtNumeric) orElse
Json.fromJson(json \ "QualitativeOutcome")(fmtQualitative)
)
}
}
最佳答案
我认为这很简单,如果您想避免为每个显式子类型编写代码,也许可以通过反射来实现,直接使用jackson或其他具有反射支持的json库。或编写自己的宏以从子类型列表中生成格式。
关于json - 在Scala的剧本中使用Json序列化处理具有多个案例类(和类型)的特质,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18454721/