【问题标题】:Scala, PlayFramework - No implicit Format available for AnyScala,PlayFramework - 没有可用于任何隐式格式
【发布时间】:2017-09-15 06:58:41
【问题描述】:

我有一个案例类和隐式格式如下:

case class Foo(x:String, y:Any)
implicit val fooFormat = Json.format[Foo]

我想将类 Foo 转换为 Json,但是,我收到错误 没有任何可用的隐式格式

val foo = Foo("apple", 12)
println(Json.toJson(foo))
[error] Test.scala:33: No implicit format for Any available.
[error]     implicit val fooFormat = Json.format[Foo]

那么,如何为 Any 类型提供隐式格式?

【问题讨论】:

  • 你期望它如何被序列化?由于Any 可以(字面上)任何东西,它可能有非常不同的可能序列化。顺便说一句,如果你只想序列化,你应该使用Json.writes[Foo]

标签: scala playframework implicit


【解决方案1】:

提供显式写入并处理 Any 可以是 Int、Long、Float、Double、String、Boolean 等的情况

case class Foo(x:String, y:Any)

implicit val writes = new Writes[Foo] {
  override def writes(o: Foo): JsValue = {
    Json.obj("x" -> o.x) ++ {
      o.y match {
        case a: Int => Json.obj("y" -> a)
        case a: Long => Json.obj("y" -> a)
        case a: Float => Json.obj("y" -> a)
        case a: Double => Json.obj("y" -> a)
        case a: String => Json.obj("y" -> a)
        case a: Boolean => Json.obj("y" -> a)
        case a => Json.obj("y" -> a.toString)
      }
    }
  }
}

Scala REPL

scala> Json.toJson(Foo("foo", true))
res5: play.api.libs.json.JsValue = {"x":"foo","y":true}

scala> Json.toJson(Foo("foo", 1.toFloat))
res6: play.api.libs.json.JsValue = {"x":"foo","y":1}

scala> Json.toJson(Foo("foo", (1.131313).toFloat))
res7: play.api.libs.json.JsValue = {"x":"foo","y":1.1313129663467407}

scala> Json.toJson(Foo("foo", (1.131313).toDouble))
res8: play.api.libs.json.JsValue = {"x":"foo","y":1.131313}

【讨论】:

    猜你喜欢
    • 2015-04-24
    • 2015-05-02
    • 1970-01-01
    • 2013-04-13
    • 2015-04-27
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    相关资源
    最近更新 更多