2

When I use the following code:

import JsonImpl.graphFormat
val js = Json.toJson(g)(graphFormat)

My code compiles and works fine but when I do this it doesn't work and says: "No Json serializer found for type SGraph. Try to implement an implicit Writes or Format for this type."

import JsonImpl.graphFormat
val js = Json.toJson(g)

JsonImpl is:

object JsonImpl{
    implicit val graphFormat = Json.format[SGraph]
}

I don't want to use companion object for my SGraph class. What is the problem and why it cannot find the implicit value?

3
  • Either should work, so there's something else in your code that's causing problems. Can you try adding an explicit return type to the instance definition, and then maybe -Xlog-implicits? Commented Jun 14, 2015 at 13:40
  • @TravisBrown `Typing graphFormat solved it, thanks! I guess learning Scala type system is out of my abilities. there is always something! Commented Jun 14, 2015 at 17:22
  • 1
    Providing explicit type annotations for type class instances is always a good idea (it ought to be mandatory), especially when you're dealing with macros. Commented Jun 14, 2015 at 17:32

1 Answer 1

4

For the sake of completeness: Json.format is a macro, and when you're dealing with macros it's a good idea to make sure what you're getting back is appropriately statically typed:

object JsonImpl{
  implicit val graphFormat: Format[SGraph] = Json.format[SGraph]
}

In fact this is a good idea whenever you're dealing with implicit values, and it'll save you a lot of confusion (sometimes because you've done something wrong, and sometimes because the compiler has).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.