且构网

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

将任何Scala对象转换为JSON

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

鉴于要序列化为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)