-
Notifications
You must be signed in to change notification settings - Fork 17
/
CaseClassFormats.scala.template
82 lines (72 loc) · 2.73 KB
/
CaseClassFormats.scala.template
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
78
79
80
81
82
/*
* Original implementation (C) 2009-2011 Debasish Ghosh
* Adapted and extended in 2011 by Mathias Doenitz
* Adapted and extended in 2016 by Eugene Yokota
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package sjsonnew
trait CaseClassFormats {
// simple alias for reduced verbosity
private[this] type JF[A] = JsonFormat[A]
private[this] type K[A] = JsonKeyWriter[A]
[2..22#def caseClass[[#K1: K#], [#A1: JF#], Z](applyFunc: ([#A1#]) => Z, unapplyFunc: Z => Option[([#A1#])])([#key1: K1#]): JF[Z] =
caseClass1[[#K1#], [#A1#], Z](applyFunc, unapplyFunc)([#key1#])
def caseClass1[[#K1#], [#A1#], Z](applyFunc: ([#A1#]) => Z, unapplyFunc: Z => Option[([#A1#])])([#key1: K1#])(implicit [#A1: JF[A1]#], [#K1: K[K1]#]): JF[Z] = new JsonFormat[Z] {
def read[J](jsOpt: Option[J], unbuilder: Unbuilder[J]): Z = jsOpt match {
case Some(js) =>
unbuilder.beginObject(js)
val z = applyFunc(
[#unbuilder.readField[A1](K1.write(key1))#]
)
unbuilder.endObject()
z
case None =>
deserializationError("Expected JsObject but found None")
}
def write[J](obj: Z, builder: Builder[J]): Unit = {
val t = unapplyFunc(obj).get
builder.beginObject()
[#builder.addField(K1.write(key1), t._1)#
]
builder.endObject()
}
}
def caseClassArray1[[#A1#], Z](applyFunc: ([#A1#]) => Z, unapplyFunc: Z => Option[([#A1#])])(implicit [#A1: JF[A1]#]): JF[Z] = {
new JsonFormat[Z] {
def write[J](t: Z, builder: Builder[J]): Unit = {
val x = unapplyFunc(t).get
builder.beginArray()
[#A1.write(x._1, builder)#
]
builder.endArray()
}
def read[J](jsOpt: Option[J], unbuilder: Unbuilder[J]): Z =
jsOpt match {
case Some(js) =>
unbuilder.beginArray(js)
[#val a1 = unbuilder.nextElement#
]
val xs = applyFunc([#A1.read(Some(a1), unbuilder)#])
unbuilder.endArray()
xs
case None =>
applyFunc([#A1.read(None, unbuilder)#])
}
}
}
def caseClassArray[[#A1: JF#], Z](applyFunc: ([#A1#]) => Z, unapplyFunc: Z => Option[([#A1#])]): JF[Z] =
caseClassArray1[[#A1#], Z](applyFunc, unapplyFunc)
#
]
}