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
66
67
68
69
70
71
72
73
74
75
76
77
|
package spray.json
import org.scalatest._
class ProductTypeFormatTests
extends FlatSpec
with FormatTests
with DerivedFormats
with DefaultJsonProtocol {
case class A()
case class B(x: Int, b: String, mp: Map[String, Int])
case class C(b: B)
case object D
case class E(d: D.type)
case class F(x: Int)
case class G(f: F)
implicit val aFormat: RootJsonFormat[A] = jsonFormat[A]
implicit val bFormat: RootJsonFormat[B] = jsonFormat[B]
implicit val cFormat: RootJsonFormat[C] = jsonFormat[C]
implicit val dFormat: RootJsonFormat[D.type] = jsonFormat[D.type]
implicit val eFormat: RootJsonFormat[E] = jsonFormat[E]
"No-parameter product" should behave like checkRoundtrip(A(), "{}")
"Simple parameter product" should behave like checkRoundtrip(
B(42, "Hello World", Map("a" -> 1, "b" -> -1024)),
"""{ "x": 42, "b": "Hello World", "mp": { "a": 1, "b": -1024 } }"""
)
"Nested parameter product" should behave like checkRoundtrip(
C(B(42, "Hello World", Map("a" -> 1, "b" -> -1024))),
"""{"b" :{ "x": 42, "b": "Hello World", "mp": { "a": 1, "b": -1024 } } }"""
)
"Case object" should behave like checkRoundtrip(
D,
"{}"
)
"Case object as parameter" should behave like checkRoundtrip(
E(D),
"""{"d":{}}"""
)
// custom format for F, that inverts the value of parameter x
implicit val fFormat: RootJsonFormat[F] = new RootJsonFormat[F] {
override def write(f: F): JsValue = JsObject("y" -> f.x.toJson)
override def read(js: JsValue): F =
F(js.asJsObject.fields("y").convertTo[Int])
}
"Overriding with a custom format" should behave like checkRoundtrip(
F(2),
"""{"y":2}"""
)
implicit val gFormat: RootJsonFormat[G] = jsonFormat[G]
"Derving a format with a custom child format" should behave like checkRoundtrip(
G(F(2)),
"""{"f": {"y":2}}"""
)
case class H(x: Boolean)
case class I(h: H)
// there is no format defined for H, Magnolia will generate one automatically
implicit val iFormat: RootJsonFormat[I] = jsonFormat[I]
"Deriving a format that has no implicit child formats available" should behave like checkRoundtrip(
I(H(true)),
"""{"h": {"x":true}}"""
)
}
|