Anorm(Scala)如何从联合表中返回Json?

问题描述 投票:1回答:1

我正在尝试将2个表链接在一起并从中返回json,不幸的是,文档和在线对此并不十分清楚,因此,如果您知道如何解决此问题,请提供一个我可以学习的摘录。

我在下面的json调用中难以呈现def All: List[(Country, City)]{....}参数:

这是我想要返回json的方式:

Ok(Json.obj("success" -> true, "CountryAndCities" -> CountryAndCities.All)

All正在:

package models

import play.api.db._
import play.api.Play.current

import anorm._
import anorm.SqlParser._

case class Country(id: Option[Int] = None, name: String)
case class City(id: Option[Int] = None, countryId: Int, name: String, population: Int)

object Country {

  val simple: RowParser[Country] = {
    get[Option[Int]]("country.id") ~
    str("country.name") map {
      case id~name => Country(id, name)
    }
  }
}

object City {

  def All: List[(Country, City)] = {

    DB.withConnection { implicit connection =>

      SQL(
        """
          SELECT *
          FROM city
            INNER JOIN country ON city.country_id = country.id
        """
      ).as(City.withCountry *)
    }
  }
}
json scala playframework anorm
1个回答
0
投票

因此,您的代码缺少列表解析部分,为完整起见,我将其包括在内:

object City {
  def All: List[(Country, City)] = {

    DB.withConnection { implicit connection =>
      SQL(
        """
        SELECT *
        FROM city
        INNER JOIN country ON city.country_id = country.id
      """
      ).as(City.withCountry.*)
    }
  }

  def simple: RowParser[City] =
    int("city.id").? ~ int("city.countryId") ~
      str("city.name") ~ int("city.population") map {
      case id ~ countryId ~ name ~ population => City(id, countryId, name, population)
    }

  def withCountry: RowParser[(Country, City)] = simple ~ Country.simple map {
    case city ~ country => country -> city
  }
}

现在,如果要将其呈现为JSON,简单的方法是键入:

implicit val userFormat = Json.format[Country]
implicit val cityFormat = Json.format[City]

Ok(Json.arr(City.All))
© www.soinside.com 2019 - 2024. All rights reserved.