spray-json icon indicating copy to clipboard operation
spray-json copied to clipboard

Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,Object]

Open chenshaoxing opened this issue 6 years ago • 1 comments

import spray.json._ import spray.json.DefaultJsonProtocol._

val list = Map("k"->"f","n"->"r","d"->List("ffff")) println(list.toJson)

compiler error: Cannot find JsonWriter or JsonFormat type class for scala.collection.immutable.Map[String,java.io.Serializable]

I used wrong?

chenshaoxing avatar Mar 22 '19 06:03 chenshaoxing

The 'problem' here is that list is a map from String to Serializable and there is no JsonWriter that works for every Serializable.

The list is a map from String to Serializable because there are both String and List[String] values in there, and Serializable is the only thing those 2 types have in common.

val list = Map("k"->List("f"),"n"->List("r"),"d"->List("ffff")) and val list = Map("k"->"f","n"->"r","d"->"ffff") would both work, but of course are not what you want.

You could immediately create a JSON object with: JsObject("k"->"f".toJson, "d"->List("ffff").toJson)

But I would probably recommend introducing a type for whatever your map represents:

case class WhatItIs(k: String, n: String, d: List[String])
implicit val format = jsonFormat3(WhatItIs)

val list = WhatItIs("f", "r", List("ffff"))

list.toJson

raboof avatar Mar 22 '19 07:03 raboof