I need to transform a case-class to a Map based json representation using only Scala/JDK types. It is to be used as parameter for a library that I cannot change. I'm using Circe, so I can go from the case-class to a Json object, but I don't know how to get a Map[String, Object] from it.
As an example I have these case-classes:
Line(from: Point, to: Point)
Point(x: Int, y:Int)
and this value:
val line = Line(Point(10, 20), Point(20, 30))
then I'd like to get the following map:
Map(
"from" -> Map("x" -> Int(10), "y" -> Int(20)),
"to" -> Map("x" -> Int(20), "y" -> Int(30))
)
(of course, other Numbers can be present in the case classes)
So I can use
line.asJson
to get the JSon representation, but where do I go from there?
I have been trying to use
line.asJson.fold()
, or foldWith()
but I get stuck when trying to process JsonNumber. I cannot seem to get
the actual value (other than randomly trying the toDouble()
, toInt()
... methods and see if one returns a value).