我在理解如何序列化类型时遇到了问题。
让我们说,我习惯于以这种方式序列化:
类:
case class LocalizedItem(itemId:String, var value:String)
{
def this(itemId:Option[String]) = this(itemId.getOrElse(null), "")
def this(itemId:String) = this(itemId, "")
}在我的格式中我是这样做的:
trait ProductFormats extends ErrorFormats {
implicit val localizedItemFormat = new Format[LocalizedItem]{
def writes(item: LocalizedItem):JsValue = {
Json.obj(
"itemId" -> item.itemId,
"value" -> item.value
)
}
def reads(json: JsValue): JsResult[LocalizedItem] =
JsSuccess(new LocalizedItem(
(json \ "itemId").as[String],
(json \ "value").as[String]
))
}我的问题是,如何对接收泛型项/类型的对象使用相同的模式(泛型将以LocalizedItem的方式实现写入/读取)
例如:
case class DTOResponse[T](d: T) {
def isError = false
def get() = d }当试图以这种方式实现时:
implicit val dtoResponseFormat = new Format[DTOResponse] {
def writes(item: DTORespons):JsValue = {
Json.obj(
"itemId" -> item.itemId,
"value" -> item.value
) }我收到错误:
class DTOResponse takes type parameters 发布于 2014-03-10 09:36:59
与…有关的东西:
implicit def dtoResponseFormat[T: Format] = new Format[DTOResponse[T]] {
val tFormatter: Format[T] = implicitly[Format[T]]
def writes(item: DTOResponse):JsValue = {
Json.obj(
"itemId" -> tFormatter.writes(item.get())
)
}
}这里的假设是,您也需要格式化T类型的值。如果没有,则可以删除类型约束。
https://stackoverflow.com/questions/22295856
复制相似问题