forked from IainHull/resttest
/
JsonExtractors.scala
65 lines (55 loc) · 1.91 KB
/
JsonExtractors.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package org.iainhull.resttest
import play.api.libs.json.JsValue
import play.api.libs.json.JsPath
import play.api.libs.json.Reads
import play.api.libs.json.JsArray
import play.api.libs.json.Json
trait JsonExtractors {
import Extractors._
/**
* Extract a path from a json document and deserialise it to a List
*/
def jsonToList[T: Reads](json: JsValue, path: JsPath = JsPath): Seq[T] = {
path(json) match {
case Seq(array: JsArray) => array.as[List[T]](Reads.list[T])
case seq: Seq[JsValue] => seq map (_.as[T])
}
}
/**
* Extract a path from a json document and deserialise it to a value
*/
def jsonToValue[T: Reads](json: JsValue, path: JsPath = JsPath): T = {
path.asSingleJson(json).as[T]
}
/**
* Extract the response body as a json document
*/
val JsonBody = BodyText andThen Json.parse as "JsonBody"
/**
* Extract the response body as an object.
*/
def jsonBodyAs[T: Reads : reflect.ClassTag]: Extractor[T] = jsonBodyAs(JsPath)
/**
* Extract a portion of the response body as an object.
*
* @param path the path for the portion of the response to use
*/
def jsonBodyAs[T: Reads : reflect.ClassTag](path: JsPath) = {
val tag = implicitly[reflect.ClassTag[T]]
JsonBody andThen (jsonToValue(_, path)) as (s"jsonBodyAs[${tag.runtimeClass.getSimpleName}]")
}
/**
* Extract the response body as a List of objects.
*/
def jsonBodyAsList[T: Reads](implicit tag : reflect.ClassTag[T]): Extractor[Seq[T]] = jsonBodyAsList(JsPath)
/**
* Extract a portion of the response body as a List of objects.
*
* @param path the path for the portion of the response to use
*/
def jsonBodyAsList[T: Reads : reflect.ClassTag](path: JsPath) = {
val tag = implicitly[reflect.ClassTag[T]]
JsonBody andThen (jsonToList(_, path)) as (s"jsonBodyAsList[${tag.runtimeClass.getSimpleName}]")
}
}
object JsonExtractors extends JsonExtractors