Yaroslav
Yaroslav

Reputation: 4659

Serialize Map[String, Any] with spray json

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

Upvotes: 20

Views: 15928

Answers (2)

Emmanuel Ballerini
Emmanuel Ballerini

Reputation: 684

Another option, which should work in your case, is

import spray.json._
import DefaultJsonProtocol._

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

Upvotes: 8

Gangstead
Gangstead

Reputation: 4182

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.

Upvotes: 29

Related Questions