Why does this json4s code work in scala repl but not compiled?

I am converting json like string to json and the following code works in scala repl

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.JsonDSL.WithDouble._
import org.json4s.native.JsonMethods._

val value = "{100:1.50;500:1.00;1000:0.50}"

val data = value.stripPrefix("{").stripSuffix("}").split(";").map(a => {
  val b = a.split(":")
  (b(0),b(1))
}).toMap
compact(render(data))

      

But when it is compiled I get the following error

[error] ... type mismatch;
[error]  found   : scala.collection.immutable.Map[String,String]
[error]  required: org.json4s.JValue
[error]     (which expands to)  org.json4s.JsonAST.JValue
[error]       compact(render(data))
[error]                      ^

      

Why is this and how can I fix it?

I suspect there is something with the type system over my head.

+3


source to share


1 answer


render()

is imported from JsonMethods._

, and actually requires a JValue. You have imported implicit map2jvalue

two of these imports twice import org.json4s.JsonDSL._

and import org.json4s.JsonDSL.WithDouble._

.

I suspect the compiler didn't find the implicit one because of the ambiguous import, try to be more selective: the third import seems like overkill (the one with JsonDSL.WithDouble._

).



Sometimes you can run scalac with -Xlog-implicits to understand why implicits are not being used.

+2


source







All Articles