Search code examples
scalacharplay-json

No instance of play.api.libs.json.Format is available for scala.Char in the implicit scope


I have a case class:

case class Status(cmpId: String, stage: String, status: String, outputPath: String, message: String, delimiter: Char = ',')

I am using : "com.typesafe.play" %% "play-json" % "2.7.2"

and have written below formats:

implicit val formats = DefaultFormats

implicit val emStatusFormat =Json.format[EmStatus]

but still getting an error:

 No instance of play.api.libs.json.Format is available for scala.Char in the implicit scope

Can anyone help me resolve this issue.


Solution

  • You try to convert this format:

    Status("cmpId value", "stage value", "status value", "outputPath value", "message value", ',')
    

    into JSON.

    Play JSON (with format generation) would like it be converted into:

    {
      "cmpId": "cmpId value",
      "stage": "stage value",
      "status": "status value",
      "outputPath": "outputPath value",
      "message": "message value",
      "delimiter": ???
    }
    

    Exactly - how should Char be encoded? Is it a single character String? Is it an integer of 1 byte size? There is no common convention for this, which is why Play JSON didn't provided any codec for it.

    But you can:

    import play.api.libs.json.Format
    implicit val charFormat: Format[Char] = ... // your implementation
    

    Once you provide it, compilation will succeed.

    You can:

    • write it by hand:
      implicit val charFormat: Format[Char] = new Format[Char]{
        /* implement required methods */
      }
      
    • use another codec to generate it
      import play.api.libs.functional.syntax._
      implicit val charFormat: Format[Char] = implicitly[Format[String]].inmap[Char](_.head, _.toString)