I'm using Scalatra and Squeryl to make a Single Page Application example, so I need my Scalatra Servlet always returning JSON. It's working perfectly when serializing an object with no relations.
I have a class Address that has a ManyToOne relationship with the class City:
class City(val id: Long, val name: String) extends KeyedEntity[Long] {
def this() = this(0, "")
}
class Address(val id: Long, val street: String, val number: Int, val city_id: Long)
extends KeyedEntity[Long] {
def this() = this(0, "", 0, 0)
lazy val city = SpaDb.cities2Addresses.rightStateful(this)
}
object SpaDb extends Schema {
val cities = table[City]("cities")
val addresses = table[Address]("addresses")
val cities2Addresses = oneToManyRelation(cities, addresses).via(_.id === _.city_id)
}
And that's my Servlet:
class SpaServlet extends SpaStack with JacksonJsonSupport {
before() {
contentType = formats("json")
}
get("/addresses") {
Address.all //return all addresses
}
}
When the servlet serializes the object Address, it serializes all attributes, but not the relationship. The result is:
{"id":1,"street":"Street 1","city_id":1}
And what I'd like to receive is:
{"id":1,"street":"Street 1","city_id":1, "city": {"id":1,"name":"MyCity"}}
What can I do to create the json this way?