Scalatra将对象序列化为JSON,但其关系未序列化

时间:2013-05-20 20:24:56

标签: scala squeryl scalatra

我正在使用Scalatra和Squeryl制作单页应用程序示例,因此我需要我的Scalatra Servlet始终返回JSON。在序列化没有关系的对象时,它可以正常工作。

我有一个类地址与City类具有ManyToOne关系:

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序列化对象Address时,它会序列化所有属性,但不会序列化关系。结果是:

{"id":1,"street":"Street 1","city_id":1}

我想收到的是:

{"id":1,"street":"Street 1","city_id":1, "city": {"id":1,"name":"MyCity"}}

如何以这种方式创建json?

0 个答案:

没有答案