Convert any Scala object to JSON

匿名 (未验证) 提交于 2019-12-03 02:48:02

问题:

I am using latest version of Play Framework and it's JSON lib like this Json.toJson(obj). But toJson is not capable of converting any Scala object to JSON, because the structure of data is unknown. Someone suggested using case convert, but here my Scala knowledge falls short. The data comes from database, but the structure of table is not known.

Where should I look further to create convert such unknown data structure to JSON?

回答1:

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) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!