19

如何使用 spray-json 序列化 Map[String, Any]?我试试

val data = Map("name" -> "John", "age" -> 42)
import spray.json._
import DefaultJsonProtocol._
data.toJson

它说Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,Any]

4

2 回答 2

29

这是我用来执行此任务的隐式转换器:

  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
    }
  }

它改编自Spray 用户组中的这篇文章,但我无法获得也不需要将嵌套的序列和映射写入 Json,因此我将它们取出。

于 2014-09-18T15:35:53.697 回答
8

另一种选择,应该适用于您的情况,是

import spray.json._
import DefaultJsonProtocol._

data.parseJson.convertTo[Map[String, JsValue]]
于 2015-04-14T20:06:38.757 回答