且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将任何 Scala 对象转换为 JSON

更新时间:2023-02-15 17:46:34

鉴于您想要序列化为 JSON 的类型数量有限,这应该可行:

Given that there is only a limited number of types you want to serialize to JSON, this should work:

object MyWriter {
  implicit val anyValWriter = Writes[Any] (a => a match {
    case v:String => Json.toJson(v)
    case v:Int => Json.toJson(v)
    case v:Any => Json.toJson(v.toString)
    // or, if you don't care about the value
    case _ => throw new RuntimeException("unserializeable type") 
  })
}

到那时,您可以通过在要序列化 ​​Any 的位置导入隐式值来使用它:

You can use it by then by importing the implicit value at the point where you want to serialize your Any:

import MyWriter.anyValWriter
val a: Any = "Foo"
Json.toJson(a)