我正在使用 Scalatra 和 Squeryl 制作单页应用程序示例,因此我需要我的 Scalatra Servlet 始终返回 JSON。在序列化没有关系的对象时它工作得很好。
我有一个类地址与类 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)
}
这就是我的 Servlet:
class SpaServlet extends SpaStack with JacksonJsonSupport {
before() {
contentType = formats("json")
}
get("/addresses") {
Address.all //return all addresses
}
}
当 servlet 序列化对象地址时,它会序列化所有属性,但不会序列化关系。结果是:
{"id":1,"street":"Street 1","city_id":1}
我想收到的是:
{"id":1,"street":"Street 1","city_id":1, "city": {"id":1,"name":"MyCity"}}
我该怎么做才能以这种方式创建 json?