arviman
arviman

Reputation: 5255

How to define an implicit deserializer using Play Json for generic types

I have a method accepting T and I'd like to do Json.parse(someString).as[T].

Now the T classes that I pass in have implicit formats defined such as implicit lazy val format: Format[Foo] = .... However, I'd like to be able to tell the compiler to find the implicit formats at runtime instead of complaining "No Json deserializer found for type T".

Upvotes: 0

Views: 271

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

The correct way to do this is to add a context bound on T:

def yourMethod[T: Reads](...) = ...

It won't be looking for the implicits at runtime (which Scala can't do), but won't let you call the method if there is no implicit like format available in scope. And when there is, it'll just pass it through to as and any other methods which need it.

If your method needs to serialize as well as serialize, you'll need both bounds: T: Reads: Writes or just T: Format.

Upvotes: 3

Related Questions