隐含的JsonWriter特性不起作用

时间:2017-12-28 12:48:23

标签: scala implicit spray-json

我的课程如下

trait RiskCheckStatusCode {
  def code: String
  def isSuccess: Boolean
}

object RiskCheckStatusCode {

  val SUCCESS = SuccessRiskCheckStatusCode("1.1.1")
  val FAIL = FailRiskCheckStatusCode("2.2.2")

  case class SuccessRiskCheckStatusCode(code: String) extends RiskCheckStatusCode {
    override def isSuccess = true
  }

  object SuccessRiskCheckStatusCode {
    import spray.json.DefaultJsonProtocol._
    implicit val formatter = jsonFormat1(SuccessRiskCheckStatusCode.apply)
  }

  case class FailRiskCheckStatusCode(code: String) extends RiskCheckStatusCode {
    override def isSuccess = false
  }

  object FailRiskCheckStatusCode {
    import spray.json.DefaultJsonProtocol._
    implicit val formatter = jsonFormat1(FailRiskCheckStatusCode.apply)
  }
}

现在我想将RiskCheckStatusCode列表转换为json

object Main extends App{

import spray.json._
import spray.json.DefaultJsonProtocol._

  val l = List(RiskCheckStatusCode.SUCCESS, RiskCheckStatusCode.FAIL)

  implicit object RiskCheckStatusCodeJsonFormat extends JsonWriter[RiskCheckStatusCode] {
    override def write(obj: RiskCheckStatusCode): JsValue = obj match {
      case obj: SuccessRiskCheckStatusCode => obj.toJson
      case obj: FailRiskCheckStatusCode => obj.toJson
    }
  }

  def json[T](list: T)(implicit formatter: JsonWriter[T]) = {
    print(list.toJson)
  }

  json(l)
}

但是json方法找不到jsonWriter [RiskCheckStatusCode]。 你能解释一下原因吗?也许我应该为特质类型做不同的事情?

修改 它适用于

 val l: RiskCheckStatusCode = RiskCheckStatusCode.SUCCESS

所以问题在于List [RiskCheckStatusCode],因为我有一个RiskCheckStatusCode的格式化程序,而不是List [RiskCheckStatusCode]。我尝试导入DefaultJsonProtocol,但它仍然无法正常工作。

import spray.json.DefaultJsonProtocol._

我必须改变定义吗?从

implicit object RiskCheckStatusCodeJsonFormat extends JsonWriter[RiskCheckStatusCode]

implicit object RiskCheckStatusCodeJsonFormat extends JsonWriter[List[RiskCheckStatusCode]]

错误:

Error:(28, 7) Cannot find JsonWriter or JsonFormat type class for List[com.example.status.RiskCheckStatusCode]
  json(l)

Error:(28, 7) not enough arguments for method json: (implicit formatter: spray.json.JsonWriter[List[com.example.status.RiskCheckStatusCode]])Unit.
Unspecified value parameter formatter.
  json(l)

1 个答案:

答案 0 :(得分:0)

您的代码很好,您的范围内没有toJson(它位于spray.json的包对象中)。

添加它,您的代码应该编译:

object Main extends App with DefaultJsonProtocol {

  import spray.json._

  // ...

}

此外,喷雾还有一些问题需要通过衍生格式提升JsonWriter(有关详细信息,请参阅this)。

您可以改为JsonFormat

implicit object RiskCheckStatusCodeJsonFormat extends JsonFormat[RiskCheckStatusCode] {
  override def write(obj: RiskCheckStatusCode): JsValue = obj match {
    case obj: SuccessRiskCheckStatusCode => obj.toJson
    case obj: FailRiskCheckStatusCode => obj.toJson
  }

  override def read(json: JsValue): RiskCheckStatusCode = ???
}

此外,要清除List更改的类型,RiskCheckStatusCode的定义更改为(this更多详细信息):

sealed trait RiskCheckStatusCode extends Serializable with Product