Serialize Map[String, Any] with spray json

女生的网名这么多〃 提交于 2019-11-29 12:05:01

问题


How do I serialize Map[String, Any] with spray-json? I try

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].


回答1:


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 post in 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.




回答2:


Another option, which should work in your case, is

data.parseJson.convertTo[Map[String, JsValue]]


来源:https://stackoverflow.com/questions/25916419/serialize-mapstring-any-with-spray-json

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