1

我正在使用 play framework 和 angularjs 实现库系统。假设在图书馆中搜索一本书,用户在输入字段中输入关键字值,该值由控制器从 GET 请求中接收。我需要在 MySQL 数据库中搜索书籍列表,将它们转换为 json 请求并将它们显示在使用 angularjs 实现的搜索页面中。我不明白如何使用 json 并将结果发送回网页。

GET     /books/all/search/:by/:value  controllers.Books.listBooks(by: String, value: String)



case class Book (
 bookId: String,
 title: String,
 author: String,
 category:String,
 price: Int,
 location: String,
 status: String
)

object Book{
   val bookParse = {
     get[String]("book.bookId") ~
     get[String]("book.title") ~
     get[String]("book.author") ~
     get[String]("book.category") ~
     get[Int]("book.price") ~
     get[String]("book.location") ~
     get[String]("book.status")map {
     case bookId~title~author~category~price~location~status => Book(bookId,title, author, category, price, location, status)
     }
  }


def searchByBookId(bookId: String) : List[Book]= {
  DB.withConnection {implicit connection =>
  SQL("select * from book where bookId = {bookId}").as(Book.bookParse *)
 }
}



object Books extends Controller {
 def listBooks(by: String, value:String): List[Book] =
 {
  if (by == "byBookId" )  Book.searchByBookId(value)
  else if(by == "byTitle")Book.searchByTitle(value)
  else Book.searchByAuthor(value)
 }
}

现在我需要将 List[Book] 结果发送到网页

4

1 回答 1

2
import play.api.libs.json._

implicit val bookFormat = Json.format[Book]

def listBooks(by: String, value: String) = Action {
  val books = if (by == "byBookId" ) Book.searchByBookId(value)
    else if(by == "byTitle")Book.searchByTitle(value)
    else Book.searchByAuthor(value)
  Ok(Json.toJson(books))
}

implicit val bookFormat需要在 Book 伴随对象上,或者在被调用时在范围内Json.toJson

有关 JSON 的更多文档:

http://www.playframework.com/documentation/2.2.x/ScalaJson

于 2013-10-07T22:37:29.990 回答