1
votes

I have the following code:

def test = Action {
  val Anon = new {
    val foo = "foo"
    val bar = "bar"
  }

  Ok(Json.toJson(Anon))
}

And I get this compilation error:

No Json deserializer found for type Object{val foo: String; val bar: String}. Try to implement an implicit Writes or Format for this type.

What is the quick fix for this problem? I already found another question here that relates to this error, but perhaps it was more specific/complex.

1
Without reflection, I don't see how to do that...Julien Lafont
@JulienLafont - who said anything about without reflection? But I would like not to write the code myself, but rather use a one-liner for that.ripper234
With reflection, I don't think anybody has already do that. Try to create a map name/values with Anon.getClass.getDeclaredFields for example.Julien Lafont

1 Answers

1
votes

As far as I can tell the only way is to introduce a structural type:

  type AnonType = {
    def foo:String
    def bar:String
  }

Then you can either do

implicit val writeAnon1 = 
  ((__ \ "foo").write[String] and
   (__ \ "bar").write[String])
   {anon:AnonType => (anon.foo, anon.bar)}

or

implicit val writeAnon2 = new Writes[AnonType] {
  def writes(o:AnonType) =
    Json toJson Map(
      "foo" -> o.foo,
      "bar" -> o.bar)
}