不确定如何反序列化和序列化可能改变的类型

说我有一个这样的模型:

case class Items(typeOfItems: TypeOfItems)

object Items{
  implicit val format = Json.format[Items]
}


sealed trait TypeOfItems extends Product with Serializable

object TypeOfItems {

  final case class Toy(typeOfItem : String,name : String,price : Int) extends TypeOfItems

  final case class Car(typeOfItem : String,model: String,price : Int ) extends TypeOfItems

}

我无法进行任何序列化或反序列化。我收到以下错误:

 No instance of play.api.libs.json.Format is available for model.TypeOfItems in the implicit scope (Hint: if declared in the same file,make sure it's declared before)
[error]   implicit val format = Json.format[Items]
[error]                                    ^
[error]  No Json serializer found for type model.Items. Try to implement an implicit Writes or Format for this type.
[error]     Ok(Json.toJson(Items(Toy("Toy","Doll",2))))

我不确定如何为TypeOfItems指定格式。我怎么做?

WY190521 回答:不确定如何反序列化和序列化可能改变的类型

播放2.7 中,sealed traits支持play-json

正如评论中已经提到的,您所缺少的是:

object TypeOfItems{
  implicit val format = Json.format[TypeOfItems]
}

请参阅此处的文档要求:ScalaJsonAutomated

对于Play 2.6,请参见以下答案:Noise free JSON format for sealed traits with Play 2.2 library(如标题所示,还有较旧版本的解决方案)

本文链接:https://www.f2er.com/3157774.html

大家都在问