Skip to content

Instantly share code, notes, and snippets.

@LeifWarner
Created July 24, 2012 21:39
Show Gist options
  • Save LeifWarner/3172849 to your computer and use it in GitHub Desktop.
Save LeifWarner/3172849 to your computer and use it in GitHub Desktop.
lift-json trait for scalatra
package org.scalatra
package liftjson
import scala.xml.XML
import net.liftweb.json._
import net.liftweb.json.Xml.toXml
trait JsonSupport extends ApiFormats {
/**
* If a request is made with a parameter in jsonpCallbackParameterNames it will
* be assumed that it is a JSONP request and the json will be returned as the
* argument to a function with the name specified in the corresponding parameter.
*
* By default no parameterNames will be checked
*/
def jsonpCallbackParameterNames: Iterable[String] = Nil
override protected def renderPipeline = ({
case jv: JValue if format == "xml" =>
contentType = "application/xml"
XML.write(response.writer, <resp>{toXml(jv)}</resp>, response.characterEncoding.get, true, null)
case jv : JValue =>
contentType = "application/json"
// JSON should always be utf8
response.characterEncoding = Some("UTF-8")
val jsonpCallback = for {
paramName <- jsonpCallbackParameterNames
callback <- params.get(paramName)
} yield callback
val writer = response.writer
jsonpCallback match {
case some::_ =>
// Status must always be 200 on jsonp, since its loaded in a <script> tag.
status = 200
writer write some
writer write '('
Printer.compact(render(jv), writer)
writer write ");"
case _ =>
Printer.compact(render(jv), writer)
}
() // Done writing response.
}: RenderPipeline) orElse super.renderPipeline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment