I’m trying to implement (de)serialization from Scala case classes to Maps (field_name -> field_value). The problem is I don’t know how to create a function, that would take a case class type and a map, instantiate, populate and return it. I’ve seen this done in some JSON libraries, but I don’t get the code.
I’m trying to implement (de)serialization from Scala case classes to Maps (field_name -> field_value).
Share
Doing this for a particular case class is trivial:
But I’m guessing that you want to create something that works for any case class, where you don’t necessarily know what the names of the values are?
In which case, you’re going to have to take a look at reflection (added in Scala 2.10.0):
http://docs.scala-lang.org/overviews/reflection/overview.html
You can use reflection to iterate over the members of a class, find out what their names are and then create your map. For example: