Json CustomSerializer

84 views
Skip to first unread message

Tom Peck

unread,
May 16, 2013, 4:29:33 AM5/16/13
to scalat...@googlegroups.com
Hi Guys,
I have a working controller which is happily serializing case classes to JSON.  The problem is that I have some non-case class models that I need to render as well.

I'm attempting to follow the Json4S guide here: https://github.com/json4s/json4s (specifically the serializing non-supported types), but all I get is a toString() of my model object.

Here is a snippet of my controller:

class MainServlet extends ScalatraServlet with JacksonJsonSupport {
  implicit override val jsonFormats: Formats = DefaultFormats + new TestSerializer

  get("/foo") {
    Ok(new Test(123))
  }
}

class Test(val i: Int)

class TestSerializer extends CustomSerializer[Test](format => (
  {
    case JObject(JField("i", JInt(i)) :: Nil) =>
      new Test(i.toInt)
  },
  {
    case x: Test =>
      JObject(JField("i", JInt(x.i)) :: Nil)
  }
  ))

Ivan Porto Carrero

unread,
May 16, 2013, 11:02:47 AM5/16/13
to scalat...@googlegroups.com
if you make the request with the Accept header set to application/json or add ?format=json as query param it will come out as json

-- 
Ivan Porto Carrero

--
You received this message because you are subscribed to the Google Groups "scalatra-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scalatra-use...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Tom Peck

unread,
May 16, 2013, 11:24:24 AM5/16/13
to scalat...@googlegroups.com
Apologies - I missed out this from my snippet:

  before() {
    contentType = formats("json")
  }

  I'm also setting the header for my unit tests like this, but to no avail.

  def getJson[A](url: String)(f : => A) = submit("GET", url, headers = Map("Accept" -> "application/json"))(f)

Cheers
-Tom
Reply all
Reply to author
Forward
0 new messages