1

I am working on implementation of library system using play framework and angularjs. suppose to search for a book in the library the user enters the keyword value in the input field, this value is received by the controller from the GET request. I need to search the MySQL database for the list of the books, convert them to json request and display them back in the search page which is implemented using angularjs. I don't understand how to use json and send the result back to the web page.

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)
 }
}

Now i need to send the List[Book] result to the web page

1 Answer 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))
}

The implicit val bookFormat needs to be either on the Book companion object, or in scope when Json.toJson is called.

More documentation on JSON:

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.