0

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).

  • 3
    Why Circe? There are ways that let you do it using only build-in functionalities: https://stackoverflow.com/questions/1226555/case-class-to-map-in-scala or https://stackoverflow.com/questions/20684572/scala-convert-map-to-case-class/31962258 In Scala 2.13 this could be basically one-liner (`value.productElementNames zip value.productIterator).toMap`). – Mateusz Kubuszok May 05 '20 at 19:25
  • I'd prefer to go through Circe as it will do some normalization on datatypes, e.g., java8 date/time values are converted etc. The library I'm using does use them as Json in the end. – user1982997 May 06 '20 at 06:04

0 Answers0