Convert any Scala object to 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")
})
}
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)
Using json4s, you can import the package:
import org.json4s.DefaultFormats
import org.json4s.native.Serialization.write
Then create an implicit variable inside your trait:
implicit val formats: DefaultFormats = DefaultFormats
And finally, in your method, use it:
write(myObject)