>我有如下类
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)
}
}
现在我想将风险检查状态代码列表转换为 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]。我尝试导入默认Json协议,但它仍然不起作用。
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)
你的代码很好,你只是在你的范围内没有toJson
(它位于spray.json
的包对象中)。
添加它,您的代码应该编译:
object Main extends App with DefaultJsonProtocol {
import spray.json._
// ...
}
此外,喷雾在通过衍生格式提升JsonWriter
方面存在一些问题(有关详细信息,请参阅此处)。
您可以改为切换到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
的定义更改为(这解释了更多详细信息):
sealed trait RiskCheckStatusCode extends Serializable with Product