Reputation: 2360
I'm writing test for some JSON restful API using Scalatra, a snippet looks like following
class MyScalatraServletTests extends ScalatraSuite with FunSuite {
test("An valid request should return 200") {
get ("/rest/json/accc/B1Q4K3/1") {
status should equal (200)
body should include ("TEST")
}
}
}
The body expected is a JSON serialised by Scalatra through its JSON support. My question is how can I convert the body back to the same case class instance in scala, and simplify the test greatly?
Upvotes: 4
Views: 3338
Reputation: 1285
json4s can be used directly to extract case classes from JSON values.
import org.json4s._
import org.json4s.jackson.JsonMethods._
val parsedBody = parse(body)
parsedBody.extract[MyCaseClass]
You can also interrogate JSON using XPath-like expressions.
val parsedBody = parse(body)
val email = (parsedBody \ "user" \ "email").values
email should be ("[email protected]")
You can call .values
to get primitive Scala values (String
s, Int
s, etc) from JValue
s (json4s' internal representation of a JSON document).
See the json4s introduction for examples of all of these.
Upvotes: 2
Reputation: 10145
I'm not sure which JSON serializer you are using or the structure of your original classes, but if you would like to deserialize JSON back to Scala, I'd recommend the Jackson Scala module:
https://github.com/FasterXML/jackson-module-scala
Upvotes: 1