spray / spray-json

A lightweight, clean and simple JSON implementation in Scala
Apache License 2.0
972 stars 190 forks source link

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

Open chenshaoxing opened 5 years ago

chenshaoxing commented 5 years ago

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?

raboof commented 5 years ago

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