json - 在Scala的剧本中使用Json序列化处理具有多个案例类(和类型)的特质

标签 json scala serialization playframework-2.0

我经常不得不对求和类型(例如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/

相关文章:

javascript - 使用 JS 库生成图表

ruby - 'json' 原生 gem 需要安装构建工具

java - 使用Java2 aws sdk时如何配置Region?

c++ - 使用 Boost 发送序列化结构但出现输入流错误

json - Alamofire CRUD POST JSON

django - 如何编写 django-rest-framework 序列化程序/字段来合并通用关系中的数据?

MYSQL REGEXP 搜索 JSON 字符串

eclipse - 斯卡拉/电梯 : Set up hotdeploy through Eclipse?

scala - 在 Scala 中执行数百万个独特转换的函数式方法是什么?

javascript - 从分割的字符串创建对象