如何将包含String和Seq [String]值的Scala映射转换为JSON?

时间:2014-06-06 19:20:45

标签: json scala playframework scala-2.10

在使用Scala的Play Framework中,如何将String和Seq [String]值的Map转换为JSON格式?以下代码为我生成错误:

val objMap = Map("id" -> "id", "tags" -> Seq("tag1", "tag2"))
Json.toJson(objMap)

产生的错误:

No Json serializer found for type scala.collection.immutable.Map[String,Object]. Try to implement an implicit Writes or Format for this type.

3 个答案:

答案 0 :(得分:6)

由于错误说明您需要为Map[String,Object]

实施写入

这就是它的样子。我编译了这段代码,看起来很好。 (我假设你正在使用Play框架)。仅供参考:那里的案例仅适用于起点。您可以根据自己的要求在其中添加/修改更多case

import play.api.libs.json._
import play.api.libs.json.Writes
import play.api.libs.json.Json.JsValueWrapper

val objMap = scala.collection.immutable.Map("id" -> "id", "tags" -> Seq("tag1", "tag2"))
Json.toJson(objMap)

implicit val writeAnyMapFormat = new Writes[Map[String, Object]] {
def writes(map: Map[String, Object]): JsValue = {
  Json.obj(map.map {
    case (s, a) => {
      val ret: (String, JsValueWrapper) = a match {
        case _: String => s -> JsString(a.asInstanceOf[String])
        case _: java.util.Date => s -> JsString(a.asInstanceOf[String])
        case _: Integer => s -> JsString(a.toString)
        case _: java.lang.Double => s -> JsString(a.toString)
        case None => s -> JsNull
        case JsArray(elements) => s -> JsArray(elements)
        case _ => s -> JsArray(a.asInstanceOf[List[Int]].map(JsNumber(_)))
      }
      ret
    }
  }.toSeq: _*)

}
}

答案 1 :(得分:3)

你可以这样做:

val objMap = Map("id" -> Json.toJson("id"), "tags" -> Json.toJson(Seq("tag1", "tag2")))
Json.toJson(objMap)

会导致这个:

 {"id":"id","tags":["tag1","tag2"]}

答案 2 :(得分:2)

你能否将地图改为

val objMap = Map("id" -> Seq("id"), "tags" -> Seq("tag1", "tag2"))

OR

您可以定义案例类和隐式写入,为案例类

定义更容易
case class Post(id: String, tags: Seq[String])

implicit val postWrites = Json.writes[Post]

val objMap = Seq(Post("id1", Seq("tag1", "tag2")))

Json.toJson(objMap)