Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chenshaoxing opened this issue Mar 22, 2019 · 1 comment

Comments

@chenshaoxing
Copy link

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
Copy link
Contributor

raboof commented Mar 22, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants