0

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?

Juliano Alves
  • 2,006
  • 4
  • 35
  • 37
  • Have you tried adding `.toList` after the `.rightStateful(this)` call (not permanently, just to test)? It sounds like your json serializer is not seeing that collection as being serializable. Along similar lines, you might try making your classes case classes. – jcern May 20 '13 at 21:18
  • @jcern I've already tried both. I think the problem is the serialization too, I'm looking into the documentation but I still haven't found a way to indicate that the relationship must be serialized. – Juliano Alves May 21 '13 at 15:08

0 Answers0