scala 使用喷雾 json 序列化 Map[String, Any]
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25916419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Serialize Map[String, Any] with spray json
提问by Yaroslav
How do I serialize Map[String, Any] with spray-json? I try
如何使用 Spray-json 序列化 Map[String, Any]?我试试
val data = Map("name" -> "John", "age" -> 42)
import spray.json._
import DefaultJsonProtocol._
data.toJson
It says Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,Any].
它说Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,Any]。
回答by Gangstead
Here's an implicit converter I used to do this task:
这是我用来完成此任务的隐式转换器:
implicit object AnyJsonFormat extends JsonFormat[Any] {
def write(x: Any) = x match {
case n: Int => JsNumber(n)
case s: String => JsString(s)
case b: Boolean if b == true => JsTrue
case b: Boolean if b == false => JsFalse
}
def read(value: JsValue) = value match {
case JsNumber(n) => n.intValue()
case JsString(s) => s
case JsTrue => true
case JsFalse => false
}
}
It was adapted from this postin the Spray user group, but I couldn't get and didn't need to write nested Sequences and Maps to Json so I took them out.
是根据Spray用户群的这个帖子改编的,但是我拿不到也不需要把嵌套的Sequences和Maps写成Json所以拿掉了。
回答by Emmanuel Ballerini
Another option, which should work in your case, is
另一个应该适用于您的情况的选择是
data.parseJson.convertTo[Map[String, JsValue]]

