-
-
Save dozed/5631680 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.scalatra.ScalatraServlet | |
import org.scalatra.json.JacksonJsonSupport | |
import java.util.Date | |
import com.novus.salat.annotations._ | |
import com.novus.salat.dao.SalatDAO | |
import com.novus.salat.global._ | |
import com.novus.salat.grater | |
import com.mongodb.casbah.Imports._ | |
import org.json4s.{CustomSerializer, Extraction, DefaultFormats} | |
import org.json4s.JsonAST.{JValue, JString} | |
import org.json4s.mongo.ObjectIdSerializer | |
case class Milestone(@Key("_id") id: Object = new ObjectId, name: String, date: Date) | |
object MilestoneDao extends SalatDAO[ Milestone , ObjectId](collection = MongoConnection()("my_db")("milestones")) | |
class MongoSample extends ScalatraServlet with JacksonJsonSupport { | |
// add support for ObjectId serialization | |
implicit val jsonFormats = DefaultFormats + new ObjectIdSerializer | |
before("/") { | |
contentType = formats("json") | |
} | |
get("/milestones") { | |
val id = new ObjectId | |
MilestoneDao.save(Milestone(id, "asd", new Date)) | |
val m = MilestoneDao.findOneById(id).get | |
// 1. use json4s' Extraction + ObjectIdSerializer from json4s-mongo | |
val v: JValue = Extraction.decompose(m) | |
// 2. use salat's grater | |
// following https://github.com/novus/salat/wiki/JSON | |
val v2: JValue = grater[Milestone].toJSON(m) | |
// 3. set content type to application/json and return Milestone | |
// the render pipeline handles the conversion | |
contentType = formats("json") | |
m | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment