1

I'm attempting to duplicate the test "automatically convert JSON for a sealed family" from ScalaJsonAutomatedSpec.scala in my local environment. However, I'm getting an error:

Error:(36, 61) Sealed trait Role is not supported: no known subclasses implicit val roleFormat: OFormat[Role] = Json.format[Role]

This is the same error I'm having in my actual work. What am I missing?

Libs used: Scala 2.12.11 Play-JSON 2.9.2

Here is the code

import play.api.libs.json._

sealed trait Role
case object Admin                            extends Role
case class Contributor(organization: String) extends Role

//#trait-custom-representation
val adminJson = Json.parse("{\n  \"admTpe\": \"admin\"\n}")

val contributorJson = Json.parse("{\n  \"admTpe\": \"contributor\",\n  \"organization\": \"Foo\"\n}")
//#trait-custom-representation

//#auto-JSON-custom-trait
import play.api.libs.json.{Json, _}

implicit val cfg: JsonConfiguration = JsonConfiguration(
  // Each JSON objects is marked with the admTpe, ...
  discriminator = "admTpe",
  // ... indicating the lower-cased name of sub-type
  typeNaming = JsonNaming { fullName =>
    fullName.drop(39 /* remove pkg */ ).toLowerCase
  }
)

// First provide instance for each sub-types 'Admin' and 'Contributor':
implicit val adminFormat = OFormat[Admin.type](Reads[Admin.type] {
  case JsObject(_) => JsSuccess(Admin)
  case _           => JsError("Empty object expected")
}, OWrites[Admin.type] { _ =>
  Json.obj()
})

implicit val contributorFormat: OFormat[Contributor] = Json.format[Contributor]

// Finally able to generate format for the sealed family 'Role'
implicit val roleFormat: OFormat[Role] = Json.format[Role]
//#auto-JSON-custom-trait

def writeAnyRole(role: Role) = Json.toJson(role)

def readAnyRole(input: JsValue): JsResult[Role] = input.validate[Role]

val sampleContributor = Contributor("Foo")

val r = readAnyRole(contributorJson)

cchantep
  • 9,118
  • 3
  • 30
  • 41
Matt
  • 683
  • 1
  • 7
  • 9

0 Answers0