Skip to content

Instantly share code, notes, and snippets.

@huntc
Created February 5, 2014 07:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save huntc/8818682 to your computer and use it in GitHub Desktop.
Save huntc/8818682 to your computer and use it in GitHub Desktop.
Illustrates how a single Itinerary or an array of Itinerary objects can be rendered as a List[Itinerary]
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json._
case class Itinerary(name: String)
object Itinerary {
implicit val format = Json.format[Itinerary]
}
object Application extends Controller {
private val itineraryReads = Json.reads[Itinerary]
private val itinerariesReads: Reads[(List[Itinerary])] = __.read[List[Itinerary]]
def receiveJson = Action(parse.json) {
request =>
val itineraryRead: JsResult[List[Itinerary]] = itinerariesReads.reads(request.body)
.map(x => JsSuccess(x))
.recover {
case _: JsError => itineraryReads.reads(request.body).map(x => List(x))
}
.flatMap(x => x)
Logger.info(s"Received $itineraryRead, ${request.body}")
Ok("cool")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment