@@ -6,6 +6,9 @@ import scala.annotation.StaticAnnotation
6
6
7
7
import CrossVersionDefs ._
8
8
9
+ object jsonMacroInstance extends jsonMacro(false )
10
+ object jsonStrictMacroInstance extends jsonMacro(true )
11
+
9
12
/**
10
13
* "@json" macro annotation for case classes
11
14
*
@@ -21,10 +24,24 @@ import CrossVersionDefs._
21
24
* then A(4) will be serialized as '4' instead of '{"value": 4}'.
22
25
*/
23
26
class json extends StaticAnnotation {
24
- def macroTransform (annottees : Any * ): Any = macro jsonMacro.impl
27
+ def macroTransform (annottees : Any * ): Any = macro jsonMacroInstance.impl
28
+ }
29
+
30
+ /**
31
+ * "@jsonstrict" macro annotation for case classes
32
+ *
33
+ * Same as "@json" annotation, except that it always uses the default Play formatter.
34
+ * For example, if A is defined as:
35
+ *
36
+ * case class A(value: Int)
37
+ *
38
+ * then A(4) will be serialized as '{"value": 4}'.
39
+ */
40
+ class jsonstrict extends StaticAnnotation {
41
+ def macroTransform (annottees : Any * ): Any = macro jsonStrictMacroInstance.impl
25
42
}
26
43
27
- object jsonMacro {
44
+ class jsonMacro ( isStrict : Boolean ) {
28
45
def impl (c : CrossVersionContext )(annottees : c.Expr [Any ]* ): c.Expr [Any ] = {
29
46
import c .universe ._
30
47
@@ -40,8 +57,8 @@ object jsonMacro {
40
57
def jsonFormatter (className : TypeName , fields : List [ValDef ]) = {
41
58
fields.length match {
42
59
case 0 => c.abort(c.enclosingPosition, " Cannot create json formatter for case class with no fields" )
43
- case 1 =>
44
- // Only one field, use the serializer for the field
60
+ case 1 if ! isStrict => {
61
+ // use the serializer for the field
45
62
q """
46
63
implicit val jsonAnnotationFormat = {
47
64
import play.api.libs.json._
@@ -51,9 +68,11 @@ object jsonMacro {
51
68
)
52
69
}
53
70
"""
54
- case _ =>
55
- // More than one field, use Play's macro
71
+ }
72
+ case _ => {
73
+ // use Play's macro
56
74
q " implicit val jsonAnnotationFormat = play.api.libs.json.Json.format[ $className] "
75
+ }
57
76
}
58
77
}
59
78
0 commit comments