Serialize Map[String, Any] with spray json

前端 未结 2 497
南旧
南旧 2020-12-30 03:21

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

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


        
2条回答
  •  再見小時候
    2020-12-30 03:42

    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.

提交回复
热议问题