不知道如何反序列化和序列化可以更改的类型

问题描述 投票:0回答:1

说我有一个这样的模型:

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的格式。我怎么做?

scala playframework
1个回答
0
投票

播放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(如标题所示,还有较早版本的解决方案)

© www.soinside.com 2019 - 2024. All rights reserved.