【问题标题】:No instance of play.api.libs.json.Format is available for scala.Char in the implicit scopescala.Char 在隐式范围内没有可用的 play.api.libs.json.Format 实例
【发布时间】:2020-05-05 18:11:36
【问题描述】:

我有一个案例类:

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

我正在使用:"com.typesafe.play" %% "play-json" % "2.7.2"

并写了以下格式:

隐式验证格式 = DefaultFormats

隐式验证 emStatusFormat =Json.format[EmStatus]

但仍然出现错误:

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

谁能帮我解决这个问题。

【问题讨论】:

    标签: scala char play-json


    【解决方案1】:

    你尝试转换这种格式:

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

    转换成 JSON。

    播放 JSON(带格式生成)希望将其转换为:

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

    完全正确 - Char 应该如何编码?是单个字符String?它是 1 字节大小的整数吗?这没有通用的约定,这就是为什么 Play JSON 没有为其提供任何编解码器的原因。

    但你可以:

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

    一旦你提供它,编译就会成功。

    你可以:

    • 手写:
      implicit val charFormat: Format[Char] = new Format[Char]{
        /* implement required methods */
      }
      
    • 使用另一个编解码器生成它
      import play.api.libs.functional.syntax._
      implicit val charFormat: Format[Char] = implicitly[Format[String]].inmap[Char](_.head, _.toString)
      

    【讨论】:

    • 宁可使用工厂Format[Char] 而不是new Format[Char]
    • 注意,你可以用Format.of[String]代替implicitly[Format[String]]
    猜你喜欢
    • 2021-09-26
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 2014-04-02
    • 2021-02-17
    • 1970-01-01
    相关资源
    最近更新 更多