Reputation: 31164
I am building a simple web server with Scala + Play. I am having trouble figuring out how to accept and deserialize JSON requests into objects of my predefined types. I need help 1) downloading a well-supported JSON package, 2) importing the package in my code to parse the HTTP requests, and 3) actually parsing some JSON.
Here is what I am putting in my SBT file for #1:
libraryDependencies += "org.json4s" %% "json4s-native" % "3.2.9"
Here's how I'm trying to import it for #2:
import org.json4s._
import org.json4s.native.JsonMethods._
Here's where I try to parse some JSON in my action:
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.json.Json
import org.json4s._
import org.json4s.native.JsonMethods._
object Application extends Controller {
case class Credentials(username: String, password: String)
def login = Action { request =>
Ok(Json.obj("message" -> "You tried to log in as: " + parse(request.body).extract[Credentials].username))
}
}
Can anyone tell me what I am doing wrong? I am getting an error at runtime which says: "play.PlayExceptions$CompilationException: Compilation error[controllers.Application.parse.type does not take parameters]"
Upvotes: 1
Views: 1339
Reputation: 55569
You're suffering from namespace pollution. Your Application
controller inherits a parse
object from the play.api.mvc.Controller
trait, and import org.json4s.native.JsonMethods._
includes its own parse
in the namespace. I'm surprised this even compiles. Making it more explicit will work. Drop the wildcard from the import, and explicitly call JsonMethods.parse
.
As the commments suggest, this is all really unnecessary. Play's built in json libraries work pretty well, so I also suggest you read up on them and use them. There are plenty of other SO posts related to Play JSON as well.
Upvotes: 5