Lift Web Framework

Stateless JSON Sample



Here's the code:

/**
 * Respond to JSON requests in a stateless dispatch
 */
object StatelessJson {
  def init() {
    // register the JSON handler
    LiftRules.statelessDispatchTable.append {
      case r @ Req("stateless_json_call" :: Nil, _, PostRequest) => () => handleJson(r)
    }
  }

  implicit def iterableToBox[X](in: Iterable[X]): Box[X] = in.toList.headOption

  def handleJson(req: Req): Box[LiftResponse] =
  for {
    json <- req.json // get the JSON
    JObject(List(JField("command", JString(cmd)), JField("params", JString(params)))) <- json // extract the command
  } yield JavaScriptResponse(SetHtml("json_result",cmd match { // build the response
        case "show" => Text(params)
        case "textile" =>  TextileParser.toHtml(params, Empty)
        case "count" => Text(params.length+" Characters")
        case x => <b>Problem... didn't handle JSON message {x}</b>
      }))
}

Lift is Copyright 2007-2010 WorldWide Conferencing, LLC. Distributed under an Apache 2.0 License.
Lift version 2.3 built on Tue Apr 05 13:24:00 PDT 2011.
Stats: Total Memory: 507,904,000 Free Memory: 460,853,880 Open Sessions: 97
Updated At: Wed May 16 20:28:15 PDT 2012 Started At: Mon Mar 26 20:25:42 PDT 2012