简体   繁体   中英

Play JSON Reads Format for Case Objects with Sealed Traits

I have a sealed trait that encapsulates an enum type like below:

sealed trait MyType
object MyType {
  case object Type1 extends MyType
  case object Type2 extends MyType
}

I will get this as a JSON request and I'm finding it a bit difficult to read the incoming String to a case object. Here is what I have:

  implicit val myFormat: Format[MyType] = new Format[MyType] {
    override def reads(json: JsValue): JsResult[MyType] = (json \ "type").as[String] match {
      case "MyType1" => MyType.Type1
      case "MyType2" => MyType.Type2
    }
    .....
    .....

It however fails compilation saying that:

Expected JsResult[MyType] but found MyType.Type1.type

What is wrong with my approach?

Fixed it like this:

implicit val myTypeReads: Reads[MyType] = Reads {
    case JsString("MyType1") => JsSuccess(MyType1)
    case JsString("MyType2") => JsSuccess(MyType2)
    case jsValue => JsError(s"MyType $jsValue is not one of supported [${MyType.values.mkString(",")}]")
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM