使用Spray json序列化Map [String,Any] [英] Serialize Map[String, Any] with spray json

查看:160
本文介绍了使用Spray json序列化Map [String,Any]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

上面写着Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,Any].

推荐答案

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

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

它是根据Spray用户组中的这篇文章改编的,但我无法不需要,也不需要向Json编写嵌套的Sequences和Maps,所以我将它们取出.

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.

这篇关于使用Spray json序列化Map [String,Any]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆