jsonscalascalatrascalatra-sbt

how to return custom json in scalatra


Scalatra Code:

import org.scalatra._
import org.json4s.{DefaultFormats, Formats}
import org.scalatra.json._


class AppServlet extends AppStack with JacksonJsonSupport{
  protected implicit lazy val jsonFormats: Formats = DefaultFormats

  private def generateJSON():((String, String),(String, String)) = {
    val json = ("Firstname" -> "joe", "LastName" -> "cole")
    json
  }

  before() {
    contentType = formats("json")
  }

  get("/") {
    generateJSON
  }
}

I am trying to return simple json using scalatra framework and the output is something like this {"_1":{"Firstname":"joe"},"_2":{"LastName":"cole"}}. I dont need _1 or _2 to be printed. Please note i am not trying to return any objects. I just need to make my own json and then return it. It is not associated with any data model. Any help is appreciated.


Solution

  • import org.scalatra._
    import org.json4s.{DefaultFormats, Formats}
    import org.scalatra.json._
    import org.json4s._
    import org.json4s.JsonDSL._
    
    class AppServlet extends AppStack with JacksonJsonSupport{
      protected implicit lazy val jsonFormats: Formats = DefaultFormats
    
      private def generateJSON():JObject = {
        val json = ("Firstname" -> "joe") ~ ("LastName" -> "cole")
        json
      }
    
      get("/") {
        generateJSON
      }
    }