Play framework Json output issue

2019-09-06 21:25发布

问题:

I have a simple action which outputs a json object string, like this:

Ok(toJson(Map(
  "results" -> result_lists
)))

This works all right. But if I do:

Ok(toJson(Map(
  "action" -> action_string, // a Scala String
  "results" -> result_lists  // a Scala List
)))

I got

No Json serializer found for type scala.collection.immutable.Map[String,java.io.Serializable]

compilation error...what's the problem?

回答1:

As others have posted in the comments before, the type of the Map is not something which can be deserialized into Json by the framework, but you can easily get rid of the Map:

scala> val s = "hello"
s: String = hello

scala> val list = List(1,2,3)
list: List[Int] = List(1, 2, 3)

scala> Json.obj("somestring" -> s, "somemap" -> list)
res0: play.api.libs.json.JsObject = {"somestring":"hello","somemap":[1,2,3]}

The resulting object can then be returned by the action as desired.