how to return custom json in scalatra

938 views Asked by At

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.

2

There are 2 answers

0
Hassan Abbas On BEST ANSWER

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
  }
}

0
rstar On

What you create is a tuple of (String, String), that's not surprising the output is like that. You should either create a case class, or, since you use json4s, return:

// don't forget this:
// import org.json4s.JsonDSL._
("Firstname" -> "joe") ~ ("LastName" -> "cole")