首页 > 解决方案 > 使用 Playframework json 格式化密封类型参数化特征

问题描述

我有类型参数化的密封特征

sealed trait PropertyValue[T <: Property]

format我需要为 Json 序列化/反序列化编写。我试试

implicit def format[P <: Property : Format]: Format[PropertyValue[P]] = {
    Format(
      Reads(j =>
        Json.fromJson[StringPropertyValue](j)
          .orElse(Json.fromJson[NumberPropertyValue](j))
          .orElse(JsError("Undefined type"))
      ),
      Writes(o => Json.toJson(o))
    )
  }

但是我有

type mismatch;
[error]  found   : play.api.libs.json.JsResult[Product with Serializable with PropertyValue[_ >: StringProperty with NumberProperty <: Product with Serializable with Property]]
[error]  required: play.api.libs.json.JsResult[PropertyValue[P]]

有没有办法实现Reads[trait[T]]类型参数化特征?

标签: jsonscaladeserializationplayframework-2.6

解决方案


推荐阅读