How can I look up a spray-json formatter by the runtime type of a value?

220 Views Asked by At

The traditional way to use spray-json seems to be to bind all your models to appropriate JsonFormats (built-in or custom) at compile time, with the formats all as implicits. Is there a way instead to look the formatters up at runtime? I'm trying to marshal a heterogeneous list of values, and the only ways I'm seeing to do it are

  1. Write an explicit lookup (e.g. using pattern matching) that hard-codes which fomratter to use for which value type, or
  2. Something insane using reflection to find all the implicits

I'm pretty new to Scala and spray-json both, so I worry I'm missing some simpler approach.


More context: I'm trying to write a custom serializer that writes out only a specified subset of (lazy) object fields. I'm looping over the list of specified fields (field names) at runtime and getting the values by reflection (actually it's more complicated than that, but close enough), and now for each one I need to find a JsonFormat that can serialize it.

0

There are 0 best solutions below