Skip to content

Instantly share code, notes, and snippets.

@LeifWarner
Created August 10, 2012 23:50
Show Gist options
  • Save LeifWarner/3319039 to your computer and use it in GitHub Desktop.
Save LeifWarner/3319039 to your computer and use it in GitHub Desktop.
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 =>
// 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::_ =>
// JSONP is not JSON, but JavaScript.
contentType = "application/javascript"
// Status must always be 200 on JSONP, since it's loaded in a <script> tag.
status = 200
writer write some
writer write '('
Printer.compact(render(jv), writer)
writer write ");"
case _ =>
contentType = "application/json"
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