/
JsonCodecMakerSpec.scala
2156 lines (1971 loc) · 118 KB
/
JsonCodecMakerSpec.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.github.plokhotnyuk.jsoniter_scala.macros
import java.nio.charset.StandardCharsets.UTF_8
import java.time._
import java.util.{Objects, UUID}
import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros.JsonCodecMaker._
import org.scalatest.exceptions.TestFailedException
import scala.annotation.switch
import scala.util.hashing.MurmurHash3
case class UserId(id: String) extends AnyVal
case class OrderId(value: Int) extends AnyVal
object UserId2 {
type Opaque = Base with Tag
type Base = Any {
type Hack
}
trait Tag
object Opaque {
def apply(value: String): Opaque = value.asInstanceOf[Opaque]
def unapply(userId: Opaque): Option[String] = Option(userId).map(_.value)
}
final implicit class Ops(private val userId: Opaque) extends AnyVal {
def value: String = userId.asInstanceOf[String]
}
}
object OrderId2 {
type Opaque = Base with Tag
type Base = Any {
type Hack
}
trait Tag
object Opaque {
def apply(value: Int): Opaque = value.asInstanceOf[Opaque]
def unapply(orderId: Opaque): Option[Int] = Option(orderId).map(_.value)
}
final implicit class Ops(private val orderId: Opaque) extends AnyVal {
def value: Int = orderId.asInstanceOf[Int]
}
}
case class Id[A](id: A) extends AnyVal
sealed trait Weapon extends Product with Serializable
object Weapon {
final case object Axe extends Weapon
final case object Sword extends Weapon
}
case class Primitives(b: Byte, s: Short, i: Int, l: Long, bl: Boolean, ch: Char, dbl: Double, f: Float)
case class BoxedPrimitives(
b: java.lang.Byte,
s: java.lang.Short,
i: java.lang.Integer,
l: java.lang.Long,
bl: java.lang.Boolean,
ch: java.lang.Character,
dbl: java.lang.Double,
f: java.lang.Float)
case class StandardTypes(s: String, bi: BigInt, bd: BigDecimal)
class NonCaseClass(val id: Int, var name: String) {
override def hashCode(): Int = id * 31 + Objects.hashCode(name)
override def equals(obj: Any): Boolean = obj match {
case c: NonCaseClass => id == c.id && Objects.equals(name, c.name)
case _ => false
}
override def toString: String = s"NonCaseClass(id=$id,name=$name)"
}
case class JavaEnums(l: Level, il: Levels.InnerLevel)
case class JavaTypes(uuid: UUID)
object LocationType extends Enumeration {
type LocationType = Value
val IP, GPS: LocationType = Value
def extra(name: String): LocationType = Value(nextId, name)
}
case class Enums(lt: LocationType.LocationType)
case class OuterTypes(s: String, st: Either[String, StandardTypes] = Left("error"))
case class Options(os: Option[String], obi: Option[BigInt], osi: Option[Set[Int]], ol: Option[Long], ojl: Option[java.lang.Long])
case class Tuples(t1: (Int, Double, List[Char]), t2: (String, BigInt, Option[LocationType.LocationType]))
case class Arrays(aa: Array[Array[Int]], a: Array[BigInt])
case class MutableMaps(
hm: collection.mutable.HashMap[Boolean, collection.mutable.AnyRefMap[BigDecimal, Int]],
m: collection.mutable.Map[Float, collection.mutable.ListMap[BigInt, String]],
ohm: collection.mutable.OpenHashMap[Double, collection.mutable.LinkedHashMap[Short, Double]])
case class ImmutableMaps(
m: Map[Int, Double],
hm: collection.immutable.HashMap[String, collection.immutable.ListMap[Char, BigInt]],
sm: collection.immutable.SortedMap[Long, collection.immutable.TreeMap[Byte, Float]])
case class EmptyMaps(im: collection.immutable.Map[String, Int], mm: collection.mutable.Map[Long, Int])
case class GenericIterables(
s: collection.Set[collection.SortedSet[String]],
is: collection.IndexedSeq[collection.Seq[Float]],
i: collection.Iterable[Int])
case class MutableIterables(
ml: collection.mutable.Seq[collection.mutable.SortedSet[String]],
ab: collection.mutable.ArrayBuffer[collection.mutable.Set[BigInt]],
as: collection.mutable.ArraySeq[collection.mutable.LinkedHashSet[Int]],
b: collection.mutable.Buffer[collection.mutable.HashSet[Double]],
lb: collection.mutable.ListBuffer[collection.mutable.TreeSet[Long]],
is: collection.mutable.IndexedSeq[collection.mutable.ArrayStack[Float]],
ub: collection.mutable.UnrolledBuffer[collection.mutable.Iterable[Short]])
case class ImmutableIterables(
l: List[collection.immutable.ListSet[String]],
q: collection.immutable.Queue[Set[BigInt]],
is: IndexedSeq[collection.immutable.SortedSet[Int]],
s: Stream[collection.immutable.TreeSet[Double]],
v: Vector[Iterable[Long]])
case class EmptyIterables(l: List[String], a: collection.mutable.ArrayBuffer[Int])
case class MutableLongMaps(lm1: collection.mutable.LongMap[Double], lm2: collection.mutable.LongMap[String])
case class ImmutableIntLongMaps(im: collection.immutable.IntMap[Double], lm: collection.immutable.LongMap[String])
case class BitSets(bs: collection.BitSet, ibs: collection.immutable.BitSet, mbs: collection.mutable.BitSet)
case class CamelPascalSnakeKebabCases(
camelCase: Int,
PascalCase: Int,
snake_case: Int,
`kebab-case`: Int,
camel1: Int,
Pascal1: Int,
snake_1: Int,
`kebab-1`: Int)
case class Recursive(s: String, bd: BigDecimal, l: List[Int], m: Map[Char, Recursive])
case class UTF8KeysAndValues(გასაღები: String)
case class Stringified(@stringified i: Int, @stringified bi: BigInt, @stringified l1: List[Int], l2: List[Int])
case class Defaults(
st: String = "VVV",
i: Int = 1,
bi: BigInt = -1,
oc: Option[Char] = Some('X'),
l: List[Int] = collection.immutable.List(0),
a: Array[Array[Int]] = Array(Array(1, 2), Array(3, 4)),
ab: collection.mutable.ArrayBuffer[Int] = collection.mutable.ArrayBuffer(1, 2),
m: Map[Int, Boolean] = Map(1 -> true),
mm: collection.mutable.Map[String, Int] = collection.mutable.Map("VVV" -> 1),
im: collection.immutable.IntMap[String] = collection.immutable.IntMap(1 -> "VVV"),
lm: collection.mutable.LongMap[Int] = collection.mutable.LongMap(1L -> 2),
s: Set[String] = Set("VVV"),
ms: collection.mutable.Set[Int] = collection.mutable.Set(1),
bs: collection.immutable.BitSet = collection.immutable.BitSet(1),
mbs: collection.mutable.BitSet = scala.collection.mutable.BitSet(1))
case class Defaults2(
st: String = "VVV",
i: Int = 1,
bi: BigInt = -1,
oc: Option[Char] = Some('X'),
l: List[Int] = collection.immutable.List(0),
ab: collection.mutable.ArrayBuffer[Int] = collection.mutable.ArrayBuffer(1, 2),
m: Map[Int, Boolean] = Map(1 -> true),
mm: collection.mutable.Map[String, Int] = collection.mutable.Map("VVV" -> 1),
im: collection.immutable.IntMap[String] = collection.immutable.IntMap(1 -> "VVV"),
lm: collection.mutable.LongMap[Int] = collection.mutable.LongMap(1L -> 2),
s: Set[String] = Set("VVV"),
ms: collection.mutable.Set[Int] = collection.mutable.Set(1),
bs: collection.immutable.BitSet = collection.immutable.BitSet(1),
mbs: collection.mutable.BitSet = collection.mutable.BitSet(1))
case class PolymorphicDefaults[A, B](i: A = 1, cs: List[B] = Nil)
case class JavaTimeTypes(
dow: DayOfWeek,
d: Duration,
i: Instant,
ld: LocalDate,
ldt: LocalDateTime,
lt: LocalTime,
m: Month,
md: MonthDay,
odt: OffsetDateTime,
ot: OffsetTime,
p: Period,
y: Year,
ym: YearMonth,
zdt: ZonedDateTime,
zi: ZoneId,
zo: ZoneOffset)
sealed trait AdtBase extends Product with Serializable
sealed abstract class Inner extends AdtBase {
def a: Int
}
case class AAA(a: Int) extends Inner
case class BBB(a: BigInt) extends AdtBase
case class CCC(a: Int, b: String) extends Inner
case object DDD extends AdtBase
sealed trait GADT2[A] extends Product with Serializable
object GADT2 {
case class IsDir(path: String) extends GADT2[_root_.scala.Boolean]
case class Exists(path: String) extends GADT2[_root_.scala.Boolean]
case class ReadBytes(path: String) extends GADT2[_root_.scala.Array[_root_.scala.Byte]]
case class CopyOver(src: Seq[_root_.scala.Byte], path: String) extends GADT2[Int]
}
class JsonCodecMakerSpec extends VerifyingSpec {
import NamespacePollutions._
val codecOfPrimitives: JsonValueCodec[Primitives] = make
val codecOfStandardTypes: JsonValueCodec[StandardTypes] = make
val codecOfJavaEnums: JsonValueCodec[JavaEnums] = make
val codecOfJavaTypes: JsonValueCodec[JavaTypes] = make
val codecOfEnums: JsonValueCodec[Enums] = make
val codecOfOptions: JsonValueCodec[Options] = make
val codecOfTuples: JsonValueCodec[Tuples] = make
val codecOfArrays: JsonValueCodec[Arrays] = make
val codecOfMutableMaps: JsonValueCodec[MutableMaps] = make
val codecOfImmutableMaps: JsonValueCodec[ImmutableMaps] = make
val codecOfNameOverridden: JsonValueCodec[NameOverridden] = make
val codecOfRecursive: JsonValueCodec[Recursive] = make(CodecMakerConfig.withAllowRecursiveTypes(true))
val codecOfUTF8KeysAndValues: JsonValueCodec[UTF8KeysAndValues] = make
val codecOfStringified: JsonValueCodec[Stringified] = make
val codecOfADTList1: JsonValueCodec[List[AdtBase]] = make
val codecOfADTList2: JsonValueCodec[List[AdtBase]] = make(CodecMakerConfig.withDiscriminatorFieldName(_root_.scala.None))
val codecOfADTList3: JsonValueCodec[List[AdtBase]] = make(CodecMakerConfig.withRequireDiscriminatorFirst(false).withBigIntDigitsLimit(20001))
"JsonCodecMaker.make generate codes which" should {
"serialize and deserialize case classes with primitives" in {
verifySerDeser(codecOfPrimitives, Primitives(1.toByte, 2.toShort, 3, 4L, bl = true, 'V', 1.1, 2.2f),
"""{"b":1,"s":2,"i":3,"l":4,"bl":true,"ch":"V","dbl":1.1,"f":2.2}""")
}
"serialize and deserialize top-level primitives" in {
verifySerDeser(make[_root_.scala.Byte], 1.toByte, "1")
verifySerDeser(make[_root_.scala.Short], 2.toShort, "2")
verifySerDeser(make[Int], 3, "3")
verifySerDeser(make[Long], 4L, "4")
verifySerDeser(make[_root_.scala.Boolean], true, "true")
verifySerDeser(make[Char], 'V', "\"V\"")
verifySerDeser(make[Double], 1.1, "1.1")
verifySerDeser(make[Float], 2.2f, "2.2")
}
"serialize and deserialize stringified top-level primitives" in {
verifySerDeser(make[_root_.scala.Byte](CodecMakerConfig.withIsStringified(true)), 1.toByte, "\"1\"")
verifySerDeser(make[_root_.scala.Short](CodecMakerConfig.withIsStringified(true)), 2.toShort, "\"2\"")
verifySerDeser(make[Int](CodecMakerConfig.withIsStringified(true)), 3, "\"3\"")
verifySerDeser(make[Long](CodecMakerConfig.withIsStringified(true)), 4L, "\"4\"")
verifySerDeser(make[_root_.scala.Boolean](CodecMakerConfig.withIsStringified(true)), true, "\"true\"")
verifySerDeser(make[Double](CodecMakerConfig.withIsStringified(true)), 1.1, "\"1.1\"")
verifySerDeser(make[Float](CodecMakerConfig.withIsStringified(true)), 2.2f, "\"2.2\"")
}
"throw parse exception with hex dump in case of illegal input" in {
verifyDeserError(codecOfPrimitives,
"""{"b":-128,"s":-32768,"i":-2147483648,"l":-9223372036854775808,'bl':true,"ch":"V","dbl":-123456789.0,"f":-12345.0}""",
"""expected '"', offset: 0x0000003e, buf:
|+----------+-------------------------------------------------+------------------+
|| | 0 1 2 3 4 5 6 7 8 9 a b c d e f | 0123456789abcdef |
|+----------+-------------------------------------------------+------------------+
|| 00000010 | 32 37 36 38 2c 22 69 22 3a 2d 32 31 34 37 34 38 | 2768,"i":-214748 |
|| 00000020 | 33 36 34 38 2c 22 6c 22 3a 2d 39 32 32 33 33 37 | 3648,"l":-922337 |
|| 00000030 | 32 30 33 36 38 35 34 37 37 35 38 30 38 2c 27 62 | 2036854775808,'b |
|| 00000040 | 6c 27 3a 74 72 75 65 2c 22 63 68 22 3a 22 56 22 | l':true,"ch":"V" |
|| 00000050 | 2c 22 64 62 6c 22 3a 2d 31 32 33 34 35 36 37 38 | ,"dbl":-12345678 |
|+----------+-------------------------------------------------+------------------+""".stripMargin)
}
"throw parse exception in case of unexpected end of input is detected" in {
verifyDeserError(codecOfPrimitives,
"""{"b":-128,"s":-32768,"i":-2147483648,"l":-9223372036854775808,"bl":true,"ch":"V","dbl":-123456789.0,"f":""",
"""unexpected end of input, offset: 0x00000068""".stripMargin)
}
"serialize and deserialize case classes with boxed primitives" in {
verifySerDeser(make[BoxedPrimitives],
BoxedPrimitives(1.toByte, 2.toShort, 3, 4L, bl = true, 'V', 1.1, 2.2f),
"""{"b":1,"s":2,"i":3,"l":4,"bl":true,"ch":"V","dbl":1.1,"f":2.2}""")
}
"serialize and deserialize top-level boxed primitives" in {
verifySerDeser(make[_root_.java.lang.Byte], _root_.java.lang.Byte.valueOf(1.toByte), "1")
verifySerDeser(make[_root_.java.lang.Short], _root_.java.lang.Short.valueOf(2.toShort), "2")
verifySerDeser(make[_root_.java.lang.Integer], _root_.java.lang.Integer.valueOf(3), "3")
verifySerDeser(make[_root_.java.lang.Long], _root_.java.lang.Long.valueOf(4L), "4")
verifySerDeser(make[_root_.java.lang.Boolean], _root_.java.lang.Boolean.valueOf(true), "true")
verifySerDeser(make[_root_.java.lang.Character], _root_.java.lang.Character.valueOf('V'), "\"V\"")
verifySerDeser(make[_root_.java.lang.Double], _root_.java.lang.Double.valueOf(1.1), "1.1")
verifySerDeser(make[_root_.java.lang.Float], _root_.java.lang.Float.valueOf(2.2f), "2.2")
}
"serialize and deserialize stringifeid top-level boxed primitives" in {
verifySerDeser(make[_root_.java.lang.Byte](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Byte.valueOf(1.toByte), "\"1\"")
verifySerDeser(make[_root_.java.lang.Short](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Short.valueOf(2.toShort), "\"2\"")
verifySerDeser(make[_root_.java.lang.Integer](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Integer.valueOf(3), "\"3\"")
verifySerDeser(make[_root_.java.lang.Long](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Long.valueOf(4L), "\"4\"")
verifySerDeser(make[_root_.java.lang.Boolean](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Boolean.valueOf(true), "\"true\"")
verifySerDeser(make[_root_.java.lang.Double](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Double.valueOf(1.1), "\"1.1\"")
verifySerDeser(make[_root_.java.lang.Float](CodecMakerConfig.withIsStringified(true)),
_root_.java.lang.Float.valueOf(2.2f), "\"2.2\"")
}
"serialize and deserialize case classes with standard types" in {
val text = "text" * 100000
val number = "1234567890"
verifySerDeser(codecOfStandardTypes,
StandardTypes(text, BigInt(number), BigDecimal(s"$number.$number")),
s"""{"s":"$text","bi":$number,"bd":$number.$number}""")
}
"throw parse exception in case of illegal value for case classes" in {
verifyDeserError(codecOfStandardTypes, "null", "expected '{', offset: 0x00000000")
}
"serialize and deserialize top-level standard types" in {
val text =
"JavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format."
verifySerDeser(make[String], text, s""""$text"""")
verifySerDeser(make[BigInt], BigInt("123456789012345678901234567890"),
"123456789012345678901234567890")
verifySerDeser(make[BigDecimal], BigDecimal("1234567890.12345678901234567890"),
"1234567890.12345678901234567890")
}
"serialize and deserialize stringified top-level standard types" in {
verifySerDeser(make[BigInt](CodecMakerConfig.withIsStringified(true)),
BigInt("123456789012345678901234567890"), "\"123456789012345678901234567890\"")
verifySerDeser(make[BigDecimal](CodecMakerConfig.withIsStringified(true)),
BigDecimal("1234567890.12345678901234567890"), "\"1234567890.12345678901234567890\"")
}
"throw parse exception in case of duplicated key for case classe was detected" in {
verifyDeserError(codecOfStandardTypes, s"""{"s":"XXX","s":"VVV","bi":10,"bi":1,"bd":20.0,"bd":2.0}""",
"duplicated field \"s\", offset: 0x0000000e")
}
"throw parse exception in case of illegal UTF-8 encoded field names" in {
val jsonBytes = """{"s":"VVV","bi":1,"bd":1.1}""".getBytes(UTF_8)
jsonBytes(2) = 0xF0.toByte
verifyDeserError(codecOfStandardTypes, jsonBytes, "malformed byte(s): 0xf0, 0x22, 0x3a, 0x22, offset: 0x00000005")
}
"throw parse exception in case of illegal JSON escaped field names" in {
verifyDeserError(codecOfStandardTypes, "{\"\\udd1e\":\"VVV\",\"bi\":1,\"bd\":1.1}",
"illegal escape sequence, offset: 0x00000008")
}
"throw parse exception in case of missing or illegal tokens" in {
verifyDeserError(codecOfStandardTypes, """"s":"VVV","bi":1,"bd":1.1}""", "expected '{', offset: 0x00000000")
verifyDeserError(codecOfStandardTypes, """{"s""VVV","bi":1,"bd":1.1}""", "expected ':', offset: 0x00000004")
verifyDeserError(codecOfStandardTypes, """{"s":"VVV""bi":1"bd":1.1}""", "expected '}' or ',', offset: 0x0000000a")
verifyDeserError(codecOfStandardTypes, """["s":"VVV","bi":1,"bd":2}""", "expected '{', offset: 0x00000000")
verifyDeserError(codecOfStandardTypes, """{,"s":"VVV","bi":1,"bd":2}""", "expected '\"', offset: 0x00000001")
verifyDeserError(codecOfStandardTypes, """{"s":"VVV","bi":1,"bd":2]""", "expected '}' or ',', offset: 0x00000018")
verifyDeserError(codecOfStandardTypes, """{"s":"VVV","bi":1,"bd":2,}""", "expected '\"', offset: 0x00000019")
}
"serialize and deserialize Scala classes which has a primary constructor with 'var' or 'var' parameters only" in {
verifySerDeser(make[NonCaseClass], new NonCaseClass(1, "VVV"), """{"id":1,"name":"VVV"}""")
}
"serialize and deserialize Java types" in {
verifySerDeser(codecOfJavaTypes, JavaTypes(new UUID(0, 0)), """{"uuid":"00000000-0000-0000-0000-000000000000"}""")
}
"throw parse exception in case of illegal value of java types" in {
verifyDeserError(codecOfJavaTypes, """{"uuid":"00000000-XXXX-0000-0000-000000000000"}""",
"expected hex digit, offset: 0x00000012")
}
"serialize and deserialize top-level java types" in {
verifySerDeser(make[UUID], new UUID(0, 0), "\"00000000-0000-0000-0000-000000000000\"")
}
"serialize and deserialize Java types as key in maps" in {
verifySerDeser(make[Map[UUID, Int]], Map(new UUID(0, 0) -> 0),
"""{"00000000-0000-0000-0000-000000000000":0}""")
}
"serialize and deserialize Java enumerations" in {
verifySerDeser(codecOfJavaEnums, JavaEnums(Level.LOW, Levels.InnerLevel.HIGH), """{"l":"LOW","il":"HIGH"}""")
}
"serialize and deserialize Java enumerations with renamed value" in {
verifySerDeser(make[JavaEnums](CodecMakerConfig.withJavaEnumValueNameMapper(JsonCodecMaker.enforce_snake_case)),
JavaEnums(Level.LOW, Levels.InnerLevel.HIGH), """{"l":"low","il":"high"}""")
verifySerDeser(make[JavaEnums](CodecMakerConfig.withJavaEnumValueNameMapper(JsonCodecMaker.enforce_snake_case
.andThen(JsonCodecMaker.EnforcePascalCase))),
JavaEnums(Level.LOW, Levels.InnerLevel.HIGH), """{"l":"Low","il":"High"}""")
verifySerDeser(make[JavaEnums](CodecMakerConfig.withJavaEnumValueNameMapper {
case "LOW" => "lo"
case "HIGH" => "hi"
}), JavaEnums(Level.LOW, Levels.InnerLevel.HIGH), """{"l":"lo","il":"hi"}""")
}
"don't generate codecs for Java enumerations when duplicated transformed names detected" in {
assert(intercept[TestFailedException](assertCompiles {
"""make[JavaEnums](CodecMakerConfig.withJavaEnumValueNameMapper { case _ => "dup" })"""
}).getMessage.contains {
"""Duplicated JSON value(s) defined for 'com.github.plokhotnyuk.jsoniter_scala.macros.Levels.InnerLevel': 'dup'.
|Values are derived from value names of the enum that are mapped by the
|'com.github.plokhotnyuk.jsoniter_scala.macros.CodecMakerConfig.javaEnumValueNameMapper' function.
|Result values should be unique per enum class.""".stripMargin.replace('\n', ' ')
})
}
"throw parse exception in case of illegal value of Java enumeration" in {
verifyDeserError(codecOfJavaEnums, """{"l":null,"il":"HIGH"}""", "expected '\"', offset: 0x00000005")
verifyDeserError(codecOfJavaEnums, """{"l":"LO","il":"HIGH"}""", "illegal enum value \"LO\", offset: 0x00000008")
}
"serialize and deserialize top-level Java enumerations" in {
verifySerDeser(make[Level], Level.HIGH, "\"HIGH\"")
}
"serialize and deserialize Java enumerations as key in maps" in {
verifySerDeser(make[Map[Level, Int]], Map(Level.HIGH -> 0), """{"HIGH":0}""")
}
"serialize and deserialize types using a custom key codec and a custom ordering for map keys" in {
implicit val codecOfLevel: JsonKeyCodec[Level] = new JsonKeyCodec[Level] {
override def decodeKey(in: JsonReader): Level = in.readKeyAsInt() match {
case 0 => Level.LOW
case 1 => Level.HIGH
case x => in.enumValueError(x.toString)
}
override def encodeKey(x: Level, out: JsonWriter): _root_.scala.Unit = x match {
case Level.LOW => out.writeKey(0)
case Level.HIGH => out.writeKey(1)
case _ => out.encodeError("illegal enum value")
}
}
verifySerDeser(make[Map[Level, Int]], Map(Level.HIGH -> 100), """{"1":100}""")
implicit val levelOrdering: Ordering[Level] = new Ordering[Level] {
override def compare(x: Level, y: Level): Int = y.ordinal - x.ordinal
}
val codecOfOrderedLevelTreeMap = make[_root_.scala.collection.immutable.TreeMap[Level, Int]]
verifySerDeser(codecOfOrderedLevelTreeMap,
_root_.scala.collection.immutable.TreeMap[Level, Int](Level.HIGH -> 100, Level.LOW -> 10), """{"0":10,"1":100}""")
verifyDeserByCheck(codecOfOrderedLevelTreeMap, """{"0":10,"1":100}""",
check = (actual: _root_.scala.collection.immutable.TreeMap[Level, Int]) => actual.ordering shouldBe levelOrdering)
}
"serialize and deserialize types using a custom value codec and a custom ordering for set values" in {
implicit val codecOfLevel: JsonValueCodec[Level] = new JsonValueCodec[Level] {
override def decodeValue(in: JsonReader, default: Level): Level = in.readInt() match {
case 0 => Level.LOW
case 1 => Level.HIGH
case x => in.enumValueError(x.toString)
}
override def encodeValue(x: Level, out: JsonWriter): _root_.scala.Unit = x match {
case Level.LOW => out.writeVal(0)
case Level.HIGH => out.writeVal(1)
case _ => out.encodeError("illegal enum value")
}
override def nullValue: Level = null.asInstanceOf[Level]
}
implicit val levelOrdering: Ordering[Level] = new Ordering[Level] {
override def compare(x: Level, y: Level): Int = y.ordinal - x.ordinal
}
val codecOfOrderedLevelTreeSet = make[_root_.scala.collection.immutable.TreeSet[Level]]
verifySerDeser(codecOfOrderedLevelTreeSet,
_root_.scala.collection.immutable.TreeSet[Level](Level.HIGH, Level.LOW), """[0,1]""")
verifyDeserByCheck(codecOfOrderedLevelTreeSet, """[0,1]""",
check = (actual: _root_.scala.collection.immutable.TreeSet[Level]) => actual.ordering shouldBe levelOrdering)
}
"serialize and deserialize enumerations" in {
verifySerDeser(codecOfEnums, Enums(LocationType.GPS), """{"lt":"GPS"}""")
verifySerDeser(codecOfEnums, Enums(LocationType.extra("Galileo")), """{"lt":"Galileo"}""")
}
"throw parse exception in case of illegal value of enumeration" in {
verifyDeserError(codecOfEnums, """{"lt":null}""", "expected '\"', offset: 0x00000006")
verifyDeserError(codecOfEnums, """{"lt":"GLONASS"}""", "illegal enum value \"GLONASS\", offset: 0x0000000e")
}
"serialize and deserialize top-level enumerations" in {
verifySerDeser(make[LocationType.LocationType], LocationType.GPS, "\"GPS\"")
}
"serialize and deserialize enumerations as key in maps" in {
verifySerDeser(make[Map[LocationType.LocationType, Int]], Map(LocationType.GPS -> 0),
"""{"GPS":0}""")
}
"serialize and deserialize outer types using custom value codecs for primitive types" in {
implicit val customCodecOfLong: JsonValueCodec[Long] = new JsonValueCodec[Long] {
val nullValue: Long = 0
def decodeValue(in: JsonReader, default: Long): Long =
if (in.isNextToken('"')) {
in.rollbackToken()
in.readStringAsLong() // or in.readString().toLong is less efficient and less safe but more universal because can accepts escaped characters
} else {
in.rollbackToken()
in.readLong()
}
def encodeValue(x: Long, out: JsonWriter): _root_.scala.Unit =
if (x > 9007199254740992L || x < -9007199254740992L) out.writeValAsString(x)
else out.writeVal(x)
}
val codecOfLongList = make[List[Long]]
verifyDeser(codecOfLongList, List(1L, 9007199254740992L, 9007199254740993L),
"[\"1\",9007199254740992,\"9007199254740993\"]")
verifySer(codecOfLongList, List(1L, 9007199254740992L, 9007199254740993L),
"[1,9007199254740992,\"9007199254740993\"]")
implicit val customCodecOfBoolean: JsonValueCodec[_root_.scala.Boolean] = new JsonValueCodec[_root_.scala.Boolean] {
val nullValue: _root_.scala.Boolean = false
def decodeValue(in: JsonReader, default: _root_.scala.Boolean): _root_.scala.Boolean =
if (in.isNextToken('"')) {
in.rollbackToken()
val v = in.readString(null)
if ("true".equalsIgnoreCase(v)) true
else if ("false".equalsIgnoreCase(v)) false
else in.decodeError("illegal boolean")
} else {
in.rollbackToken()
in.readBoolean()
}
def encodeValue(x: _root_.scala.Boolean, out: JsonWriter): _root_.scala.Unit =
out.writeNonEscapedAsciiVal(if (x) "TRUE" else "FALSE")
}
case class Flags(f1: _root_.scala.Boolean, f2: _root_.scala.Boolean)
val codecOfFlags = make[Flags]
verifyDeser(codecOfFlags, Flags(f1 = true, f2 = false), "{\"f1\":true,\"f2\":\"False\"}")
verifySer(codecOfFlags, Flags(f1 = true, f2 = false), "{\"f1\":\"TRUE\",\"f2\":\"FALSE\"}")
verifyDeserError(codecOfFlags, "{\"f1\":\"XALSE\",\"f2\":true}", "illegal boolean, offset: 0x0000000c")
verifyDeserError(codecOfFlags, "{\"f1\":xalse,\"f2\":true}", "illegal boolean, offset: 0x00000006")
implicit val customCodecOfDouble: JsonValueCodec[Double] = new JsonValueCodec[Double] {
val nullValue: Double = 0.0f
def decodeValue(in: JsonReader, default: Double): Double =
if (in.isNextToken('"')) {
in.rollbackToken()
val len = in.readStringAsCharBuf()
if (in.isCharBufEqualsTo(len, "NaN")) Double.NaN
else if (in.isCharBufEqualsTo(len, "Infinity")) Double.PositiveInfinity
else if (in.isCharBufEqualsTo(len, "-Infinity")) Double.NegativeInfinity
else in.decodeError("illegal double")
} else {
in.rollbackToken()
in.readDouble()
}
def encodeValue(x: Double, out: JsonWriter): _root_.scala.Unit =
if (_root_.java.lang.Double.isFinite(x)) out.writeVal(x)
else out.writeNonEscapedAsciiVal {
if (x != x) "NaN"
else if (x >= 0) "Infinity"
else "-Infinity"
}
}
val codecOfDoubleArray = make[Array[Double]]
verifySerDeser(codecOfDoubleArray, _root_.scala.Array(-1e300 / 1e-300, 1e300 / 1e-300, 0.0, 1.0e10),
"[\"-Infinity\",\"Infinity\",0.0,1.0E10]")
verifyDeserError(codecOfDoubleArray, "[\"Inf\",\"-Inf\"]", "illegal double, offset: 0x00000005")
}
"serialize date time values into alternative format" in {
implicit val customCodecOfZonedDateTime: JsonValueCodec[ZonedDateTime] = new JsonValueCodec[ZonedDateTime] {
private[this] val standardCodec: JsonValueCodec[ZonedDateTime] = JsonCodecMaker.make[ZonedDateTime]
val nullValue: ZonedDateTime = null
def decodeValue(in: JsonReader, default: ZonedDateTime): ZonedDateTime = in.readZonedDateTime(default)
def encodeValue(x: ZonedDateTime, out: JsonWriter): _root_.scala.Unit =
if (x.getSecond != 0 || x.getNano != 0) out.writeVal(x)
else {
val s = writeToString(x)(standardCodec)
val i = s.indexOf(':', 13) + 3
out.writeNonEscapedAsciiVal(s"${s.substring(1, i)}:00${s.substring(i, s.length - 1)}")
}
}
verifySerDeser(make[Array[ZonedDateTime]],
_root_.scala.Array(ZonedDateTime.parse("2020-04-10T10:07:00Z"), ZonedDateTime.parse("2020-04-10T10:07:01Z")),
"[\"2020-04-10T10:07:00Z\",\"2020-04-10T10:07:01Z\"]")
}
"serialize and deserialize outer types using custom value codecs for opaque types" in {
abstract class Foo {
type Bar
}
val foo: Foo = new Foo {
type Bar = Int
}
type Bar = foo.Bar
case class Baz(bar: Bar)
implicit val customCodecOfBar: JsonValueCodec[Bar] = new JsonValueCodec[Bar] {
val nullValue: Bar = null.asInstanceOf[Bar]
def encodeValue(x: Bar, out: JsonWriter): _root_.scala.Unit = out.writeVal(x.asInstanceOf[Int])
def decodeValue(in: JsonReader, default: Bar): Bar = in.readInt().asInstanceOf[Bar]
}
verifySerDeser(make[Baz], Baz(42.asInstanceOf[Bar]), "{\"bar\":42}")
case class OpaqueTypes(uid: UserId2.Opaque, oid: OrderId2.Opaque)
implicit val customCodecOfUserId2: JsonValueCodec[UserId2.Opaque] = new JsonValueCodec[UserId2.Opaque] {
val nullValue: UserId2.Opaque = null.asInstanceOf[UserId2.Opaque]
def encodeValue(x: UserId2.Opaque, out: JsonWriter): _root_.scala.Unit = out.writeVal(x.value)
def decodeValue(in: JsonReader, default: UserId2.Opaque): UserId2.Opaque = UserId2.Opaque(in.readString(default.value))
}
implicit val customCodecOfOrderId2: JsonValueCodec[OrderId2.Opaque] = new JsonValueCodec[OrderId2.Opaque] {
val nullValue: OrderId2.Opaque = null.asInstanceOf[OrderId2.Opaque]
def encodeValue(x: OrderId2.Opaque, out: JsonWriter): _root_.scala.Unit = out.writeVal(x.value)
def decodeValue(in: JsonReader, default: OrderId2.Opaque): OrderId2.Opaque = OrderId2.Opaque(in.readInt())
}
verifySerDeser(make[OpaqueTypes],
OpaqueTypes(UserId2.Opaque("123abc"), OrderId2.Opaque(123123)), """{"uid":"123abc","oid":123123}""")
}
"serialize and deserialize outer types using custom value codecs for nested types" in {
implicit val customCodecOfEither1: JsonValueCodec[Either[String, Int]] =
new JsonValueCodec[Either[String, Int]] {
val nullValue: Either[String, Int] = null
def decodeValue(in: JsonReader, default: Either[String, Int]): Either[String, Int] = {
val t = in.nextToken()
in.rollbackToken()
if (t == '"') Left(in.readString(null))
else Right(in.readInt())
}
def encodeValue(x: Either[String, Int], out: JsonWriter): _root_.scala.Unit = x match {
case Right(i) => out.writeVal(i)
case Left(s) => out.writeVal(s)
}
}
val codecOfEitherList = make[List[Either[String, Int]]]
verifySerDeser(codecOfEitherList, List(Right(1), Left("VVV")), "[1,\"VVV\"]")
implicit val customCodecOfEither2: JsonValueCodec[Either[String, StandardTypes]] =
new JsonValueCodec[Either[String, StandardTypes]] {
val nullValue: Either[String, StandardTypes] = null
def decodeValue(in: JsonReader, default: Either[String, StandardTypes]): Either[String, StandardTypes] =
(in.nextToken(): @switch) match {
case '{' =>
in.rollbackToken()
Right(codecOfStandardTypes.decodeValue(in, codecOfStandardTypes.nullValue))
case '"' =>
in.rollbackToken()
Left(in.readString(null))
case _ =>
in.decodeError("expected '{' or '\"'")
}
def encodeValue(x: Either[String, StandardTypes], out: JsonWriter): _root_.scala.Unit =
x match {
case Left(s) => out.writeVal(s)
case Right(st) => codecOfStandardTypes.encodeValue(st, out)
}
}
val codecOfOuterTypes = make[OuterTypes]
verifySerDeser(codecOfOuterTypes, OuterTypes("X", Right(StandardTypes("VVV", 1, 1.1))),
"""{"s":"X","st":{"s":"VVV","bi":1,"bd":1.1}}""")
verifySerDeser(codecOfOuterTypes, OuterTypes("X", Left("fatal error")), """{"s":"X","st":"fatal error"}""")
verifySerDeser(codecOfOuterTypes, OuterTypes("X", Left("error")), """{"s":"X"}""") // st matches with default value
verifySerDeser(codecOfOuterTypes, OuterTypes("X"), """{"s":"X"}""")
implicit object codecOfLocationType extends JsonValueCodec[LocationType.LocationType] {
val nullValue: LocationType.LocationType = null
def decodeValue(in: JsonReader, default: LocationType.LocationType): LocationType.LocationType = {
val v = in.readInt()
try LocationType.apply(v) catch {
case _: NoSuchElementException => in.decodeError("invalid enum value: " + v)
}
}
def encodeValue(x: LocationType.LocationType, out: JsonWriter): _root_.scala.Unit = out.writeVal(x.id)
}
val codecOfEnums = make[Enums]
verifySerDeser(codecOfEnums, Enums(LocationType.GPS), """{"lt":1}""")
verifyDeserError(codecOfEnums, """{"lt":"GPS"}""", "illegal number, offset: 0x00000006")
}
"serialize and deserialize types as a JSON object or a JSON string using custom value codecs" in {
val customCodecOfStandardTypes: JsonValueCodec[StandardTypes] =
new JsonValueCodec[StandardTypes] {
val nullValue: StandardTypes = null
def decodeValue(in: JsonReader, default: StandardTypes): StandardTypes = (in.nextToken(): @switch) match {
case '{' =>
in.rollbackToken()
codecOfStandardTypes.decodeValue(in, codecOfStandardTypes.nullValue)
case '"' =>
in.rollbackToken()
readFromString(in.readString(null))(codecOfStandardTypes)
case _ =>
in.decodeError("expected '{' or '\"'")
}
def encodeValue(x: StandardTypes, out: JsonWriter): _root_.scala.Unit = x.s match {
case "VVV" => codecOfStandardTypes.encodeValue(x, out)
case "XXX" => out.writeVal(writeToString(x)(codecOfStandardTypes))
}
}
verifySerDeser(customCodecOfStandardTypes, StandardTypes("VVV", 1, 1.1), """{"s":"VVV","bi":1,"bd":1.1}""")
verifySerDeser(customCodecOfStandardTypes, StandardTypes("XXX", 1, 1.1), """"{\"s\":\"XXX\",\"bi\":1,\"bd\":1.1}"""")
}
"serialize and deserialize sequences of tuples as JSON object with duplicated keys using a custom codec" in {
val codecOfSeqOfTuples: JsonValueCodec[Seq[(String, Int)]] = new JsonValueCodec[Seq[(String, Int)]] {
override def decodeValue(in: JsonReader, default: Seq[(String, Int)]): Seq[(String, Int)] =
if (in.isNextToken('{')) {
val kvs = _root_.scala.collection.immutable.List.newBuilder[(String, Int)]
if (!in.isNextToken('}')) {
in.rollbackToken()
while ({
kvs.+=((in.readKeyAsString(), in.readInt()))
in.isNextToken(',')
}) ()
if (!in.isCurrentToken('}')) in.objectEndOrCommaError()
}
kvs.result()
} else in.readNullOrTokenError(default, '{')
override def encodeValue(kvs: Seq[(String, Int)], out: JsonWriter): _root_.scala.Unit = {
out.writeObjectStart()
kvs.foreach { case (k, v) =>
out.writeKey(k)
out.writeVal(v)
}
out.writeObjectEnd()
}
override val nullValue: Seq[(String, Int)] = Seq.empty
}
verifySerDeser(codecOfSeqOfTuples, Seq("foo" -> 1, "bar" -> 2, "foo" -> 3),"""{"foo":1,"bar":2,"foo":3}""")
}
"serialize and deserialize raw untouched bytes using a custom value codec" in {
object RawVal {
def apply(s: String) = new RawVal(s.getBytes)
implicit val codec: JsonValueCodec[RawVal] = new JsonValueCodec[RawVal] {
override def decodeValue(in: JsonReader, default: RawVal): RawVal = new RawVal(in.readRawValAsBytes())
override def encodeValue(x: RawVal, out: JsonWriter): _root_.scala.Unit = out.writeRawVal(x.bs)
override val nullValue: RawVal = new RawVal(new _root_.scala.Array[_root_.scala.Byte](0))
}
}
case class RawVal private(bs: _root_.scala.Array[_root_.scala.Byte]) {
def this(s: _root_.scala.Predef.String) = this(s.getBytes(UTF_8))
override lazy val hashCode: Int = MurmurHash3.arrayHash(bs)
override def equals(obj: Any): _root_.scala.Boolean = obj match {
case that: RawVal => _root_.java.util.Arrays.equals(bs, that.bs)
case _ => false
}
}
case class Message(param1: String, param2: String, payload: RawVal, param3: String)
verifySerDeser(make[Message],
Message("A", "B", RawVal("""{"x":[-1.0,1,4.0E20],"y":{"xx":true,"yy":false,"zz":null},"z":"Z"}"""), "C"),
"""{"param1":"A","param2":"B","payload":{"x":[-1.0,1,4.0E20],"y":{"xx":true,"yy":false,"zz":null},"z":"Z"},"param3":"C"}""")
}
"serialize and deserialize case classes with value classes" in {
case class ValueClassTypes(uid: UserId, oid: OrderId)
verifySerDeser(make[ValueClassTypes],
ValueClassTypes(UserId("123abc"), OrderId(123123)), """{"uid":"123abc","oid":123123}""")
}
"serialize and deserialize top-level value classes" in {
val codecOfUserId = make[UserId]
verifySerDeser(codecOfUserId, UserId("123abc"), "\"123abc\"")
verifySerDeser(make[OrderId], OrderId(123123), "123123")
}
"serialize and deserialize stringified top-level value classes" in {
verifySerDeser(make[OrderId](CodecMakerConfig.withIsStringified(true)), OrderId(123123), "\"123123\"")
}
"serialize and deserialize case classes with options" in {
verifySerDeser(codecOfOptions,
Options(Option("VVV"), Option(BigInt(4)), Option(Set()), Option(1L), Option(_root_.java.lang.Long.valueOf(2L))),
"""{"os":"VVV","obi":4,"osi":[],"ol":1,"ojl":2}""")
verifySerDeser(codecOfOptions,
Options(_root_.scala.None, _root_.scala.None, _root_.scala.None, _root_.scala.None, _root_.scala.None),
"""{}""")
}
"serialize and deserialize options in collections using null for None values" in {
verifySerDeser(make[Array[Option[Int]]], _root_.scala.Array(_root_.scala.None, Some(1)), "[null,1]")
verifySerDeser(make[List[Option[Int]]], List(Some(1), _root_.scala.None), "[1,null]")
verifySerDeser(make[Set[Option[Int]]], Set(Some(1), _root_.scala.None), "[1,null]")
verifySerDeser(make[Map[String, Option[Int]]], Map("VVV" -> _root_.scala.None, "WWW" -> Some(1)),
"""{"VVV":null,"WWW":1}""")
}
"don't generate codecs when options are used as keys in maps" in {
assert(intercept[TestFailedException](assertCompiles {
"JsonCodecMaker.make[Map[Option[Int], Option[String]]]"
}).getMessage.contains {
"No implicit 'com.github.plokhotnyuk.jsoniter_scala.core.JsonKeyCodec[_]' defined for 'Option[Int]'"
})
}
"serialize case classes with empty options as null when the transientNone flag is off" in {
verifySerDeser(make[Options](CodecMakerConfig.withTransientNone(false)),
Options(Option("VVV"), Option(BigInt(4)), Option(Set()), Option(1L), Option(_root_.java.lang.Long.valueOf(2L))),
"""{"os":"VVV","obi":4,"osi":[],"ol":1,"ojl":2}""")
verifySerDeser(make[Options](CodecMakerConfig.withTransientNone(false)),
Options(_root_.scala.None, _root_.scala.None, _root_.scala.None, _root_.scala.None, _root_.scala.None),
"""{"os":null,"obi":null,"osi":null,"ol":null,"ojl":null}""")
}
"serialize and deserialize top-level options" in {
val codecOfStringOption = make[Option[String]]
verifySerDeser(codecOfStringOption, Some("VVV"), "\"VVV\"")
verifySerDeser(codecOfStringOption, _root_.scala.None, "null")
}
"serialize and deserialize stringified top-level numeric options" in {
val codecOfStringifiedOption = make[Option[BigInt]](CodecMakerConfig.withIsStringified(true))
verifySerDeser(codecOfStringifiedOption, Some(BigInt(123)), "\"123\"")
verifySerDeser(codecOfStringifiedOption, _root_.scala.None, "null")
}
"throw parse exception in case of unexpected value for option" in {
val codecOfStringOption = make[Option[String]]
verifyDeserError(codecOfStringOption, """no!!!""", "expected value or null, offset: 0x00000001")
}
"serialize and deserialize case classes with tuples" in {
verifySerDeser(codecOfTuples, Tuples((1, 2.2, List('V')), ("VVV", 3, Some(LocationType.GPS))),
"""{"t1":[1,2.2,["V"]],"t2":["VVV",3,"GPS"]}""")
}
"throw parse exception in case of unexpected number of JSON array values" in {
verifyDeserError(codecOfTuples, """{"t1":[1,2.2],"t2":["VVV",3,"GPS"]}""", "expected ',', offset: 0x0000000c")
verifyDeserError(codecOfTuples, """{"t1":[1,2.2,["V"]],"t2":["VVV",3,"GPS","XXX"]}""",
"expected ']', offset: 0x00000027")
}
"serialize and deserialize top-level tuples" in {
verifySerDeser(make[(String, Int)], ("VVV", 1), "[\"VVV\",1]")
}
"serialize and deserialize stringified top-level numeric tuples" in {
verifySerDeser(make[(Long, Float, BigDecimal)](CodecMakerConfig.withIsStringified(true)),
(1L, 2.2f, BigDecimal(3.3)), "[\"1\",\"2.2\",\"3.3\"]")
}
"serialize and deserialize tuples with type aliases" in {
type I = Int
type S = String
case class Tuples(t1: (S, I), t2: (I, S))
verifySerDeser(make[Tuples], Tuples(("VVV", 1), (2, "WWW")),
"{\"t1\":[\"VVV\",1],\"t2\":[2,\"WWW\"]}")
verifySerDeser(make[(S, I)], ("VVV", 1), "[\"VVV\",1]")
}
"serialize and deserialize case classes with arrays" in {
val arrays = Arrays(_root_.scala.Array(_root_.scala.Array(1, 2), _root_.scala.Array(3, 4)),
_root_.scala.Array[BigInt](1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17))
val json = """{"aa":[[1,2],[3,4]],"a":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]}"""
verifySer(codecOfArrays, arrays, json)
verifySer(make[Arrays](CodecMakerConfig.withTransientEmpty(false)), arrays, json)
val parsedObj = readFromArray(json.getBytes(UTF_8))(codecOfArrays)
parsedObj.aa shouldBe arrays.aa
parsedObj.a shouldBe arrays.a
}
"serialize and deserialize top-level arrays" in {
val json = """[[1,2,3],[4,5,6]]"""
val arrayOfArray = _root_.scala.Array(_root_.scala.Array(1, 2, 3), _root_.scala.Array(4, 5, 6))
val codecOfArrayOfArray = make[Array[Array[Int]]]
verifySer(codecOfArrayOfArray, arrayOfArray, json)
val parsedObj = readFromArray(json.getBytes(UTF_8))(codecOfArrayOfArray)
parsedObj shouldBe arrayOfArray
}
"serialize and deserialize stringified top-level arrays" in {
val json = """[["1","2","3"],["4","5","6"]]"""
val arrayOfArray = _root_.scala.Array(_root_.scala.Array(1, 2, 3), _root_.scala.Array(4, 5, 6))
val codecOfStringifiedArrayOfArray = make[Array[Array[Int]]](CodecMakerConfig.withIsStringified(true))
verifySer(codecOfStringifiedArrayOfArray, arrayOfArray, json)
val parsedObj = readFromArray(json.getBytes(UTF_8))(codecOfStringifiedArrayOfArray)
parsedObj shouldBe arrayOfArray
}
"don't serialize fields of case classes with empty arrays" in {
val json = """{"aa":[[],[]]}"""
val arrays = Arrays(_root_.scala.Array(_root_.scala.Array(), _root_.scala.Array()), _root_.scala.Array())
verifySer(codecOfArrays, arrays, json)
val parsedObj = readFromArray(json.getBytes(UTF_8))(codecOfArrays)
parsedObj.aa shouldBe arrays.aa
parsedObj.a shouldBe arrays.a
}
"serialize fields of case classes with empty arrays when transientEmpty is off" in {
val json = """{"aa":[[],[]],"a":[]}"""
val arrays = Arrays(_root_.scala.Array(_root_.scala.Array(), _root_.scala.Array()), _root_.scala.Array())
verifySer(make[Arrays](CodecMakerConfig.withTransientEmpty(false)), arrays, json)
val parsedObj = readFromArray(json.getBytes(UTF_8))(codecOfArrays)
parsedObj.aa shouldBe arrays.aa
parsedObj.a shouldBe arrays.a
}
"throw parse exception for missing array field when the requireCollectionFields flag is on" in {
val codecOfArrays1 = makeWithRequiredCollectionFields[Arrays]
verifyDeserError(codecOfArrays1, "{}", "missing required field \"aa\", offset: 0x00000001")
verifyDeserError(codecOfArrays1, """{"aa":[[],[]]}""", "missing required field \"a\", offset: 0x0000000d")
val codecOfArrays2 = makeWithRequiredCollectionFieldsAndNameAsDiscriminatorFieldName[Arrays]
verifyDeserError(codecOfArrays2, "{}", "missing required field \"aa\", offset: 0x00000001")
verifyDeserError(codecOfArrays2, """{"aa":[[],[]]}""", "missing required field \"a\", offset: 0x0000000d")
}
"throw parse exception in case of JSON array is not properly started/closed or with leading/trailing comma" in {
verifyDeserError(codecOfArrays, """{"aa":[{1,2,3]],"a":[]}""", "expected '[' or null, offset: 0x00000007")
verifyDeserError(codecOfArrays, """{"aa":[[,1,2,3]],"a":[]}""", "illegal number, offset: 0x00000008")
verifyDeserError(codecOfArrays, """{"aa":[[1,2,3}],"a":[]}""", "expected ']' or ',', offset: 0x0000000d")
verifyDeserError(codecOfArrays, """{"aa":[[1,2,3,]],"a":[]}""", "illegal number, offset: 0x0000000e")
}
"serialize and deserialize case classes with generic Iterables" in {
val codecOfGenericIterables = make[GenericIterables]
verifySerDeser(codecOfGenericIterables,
GenericIterables(_root_.scala.collection.Set(_root_.scala.collection.SortedSet("1", "2", "3")),
_root_.scala.collection.IndexedSeq(_root_.scala.collection.Seq(1.1f, 2.2f, 3.3f)),
_root_.scala.collection.Iterable(4, 5, 6)),
"""{"s":[["1","2","3"]],"is":[[1.1,2.2,3.3]],"i":[4,5,6]}""")
verifySer(codecOfGenericIterables,
GenericIterables(_root_.scala.collection.immutable.Set(_root_.scala.collection.immutable.SortedSet("1", "2", "3")),
_root_.scala. collection.immutable.IndexedSeq(_root_.scala.collection.immutable.Seq(1.1f, 2.2f, 3.3f)),
_root_.scala.collection.immutable.Iterable(4, 5, 6)),
"""{"s":[["1","2","3"]],"is":[[1.1,2.2,3.3]],"i":[4,5,6]}""")
verifySer(codecOfGenericIterables,
GenericIterables(_root_.scala.collection.mutable.Set(_root_.scala.collection.mutable.SortedSet("1", "2", "3")),
_root_.scala.collection.mutable.IndexedSeq(_root_.scala.collection.mutable.Seq(1.1f, 2.2f, 3.3f)),
_root_.scala.collection.mutable.Iterable(4, 5, 6)),
"""{"s":[["1","2","3"]],"is":[[1.1,2.2,3.3]],"i":[4,5,6]}""")
}
"serialize and deserialize case classes with mutable Iterables" in {
verifySerDeser(make[MutableIterables],
MutableIterables(
_root_.scala.collection.mutable.Seq(_root_.scala.collection.mutable.SortedSet("1", "2", "3")),
_root_.scala.collection.mutable.ArrayBuffer(_root_.scala.collection.mutable.Set[BigInt](4),
_root_.scala.collection.mutable.Set.empty[BigInt]),
_root_.scala.collection.mutable.ArraySeq(_root_.scala.collection.mutable.LinkedHashSet(5, 6),
_root_.scala.collection.mutable.LinkedHashSet.empty[Int]),
_root_.scala.collection.mutable.Buffer(_root_.scala.collection.mutable.HashSet(7.7)),
_root_.scala.collection.mutable.ListBuffer(_root_.scala.collection.mutable.TreeSet(9L, 10L)),
_root_.scala.collection.mutable.IndexedSeq(_root_.scala.collection.mutable.ArrayStack(11.11f, 12.12f)),
_root_.scala.collection.mutable.UnrolledBuffer(_root_.scala.collection.mutable.Iterable(13.toShort, 14.toShort))),
"""{"ml":[["1","2","3"]],"ab":[[4],[]],"as":[[5,6],[]],"b":[[7.7]],"lb":[[9,10]],"is":[[11.11,12.12]],"ub":[[13,14]]}""")
}
"serialize and deserialize case classes with immutable Iterables" in {
verifySerDeser(make[ImmutableIterables],
ImmutableIterables(List(_root_.scala.collection.immutable.ListSet("1")), _root_.scala.collection.immutable.Queue(Set[BigInt](4)),
IndexedSeq(_root_.scala.collection.immutable.SortedSet(5, 6, 7), _root_.scala.collection.immutable.SortedSet()),
Stream(_root_.scala.collection.immutable.TreeSet(8.9)), Vector(Iterable(10L, 11L))),
"""{"l":[["1"]],"q":[[4]],"is":[[5,6,7],[]],"s":[[8.9]],"v":[[10,11]]}""")
}
"serialize and deserialize case class fields with empty iterables when transientEmpty is off" in {
verifySerDeser(make[EmptyIterables](CodecMakerConfig.withTransientEmpty(false)),
EmptyIterables(List(), _root_.scala.collection.mutable.ArrayBuffer()), """{"l":[],"a":[]}""")
verifySerDeser(make[EmptyIterables](CodecMakerConfig.withTransientEmpty(false)),
EmptyIterables(List("VVV"), _root_.scala.collection.mutable.ArrayBuffer(1)), """{"l":["VVV"],"a":[1]}""")
}
"throw parse exception for missing collection field when the requireCollectionFields flag is on" in {
verifyDeserError(makeWithRequiredCollectionFields[EmptyIterables],
"{}", "missing required field \"l\", offset: 0x00000001")
case class NestedIterables(lessi: List[Either[String, Set[Int]]])
val codecOfNestedIterables = make[NestedIterables](CodecMakerConfig.withFieldNameMapper {
case "b" => "value"
case "a" => "value"
}.withRequireCollectionFields(true).withTransientEmpty(false))
verifyDeserError(codecOfNestedIterables, """{"lessi":[{"type":"Left"}]}""",
"missing required field \"value\", offset: 0x00000018")
verifyDeserError(codecOfNestedIterables, """{"lessi":[{"type":"Right"}]}""",
"missing required field \"value\", offset: 0x00000019")
}
"serialize and deserialize case classes with collection fields that has default values when the requireCollectionFields flag is on" in {
case class IterablesWithDefaults(l: List[Int] = _root_.scala.collection.immutable.Nil, s: Set[Option[String]] = Set())
verifySerDeser(makeWithRequiredCollectionFields[IterablesWithDefaults],
IterablesWithDefaults(), "{}")
}
"serialize and deserialize case classes with empty Iterables when the requireCollectionFields flag is on and transientEmpty is off" in {
verifySerDeser(makeWithRequiredCollectionFields[EmptyIterables],
EmptyIterables(List(), _root_.scala.collection.mutable.ArrayBuffer()), """{"l":[],"a":[]}""")
}
"deserialize null values as empty Iterables for fields with collection types" in {
verifyDeser(make[EmptyIterables],
EmptyIterables(List(), _root_.scala.collection.mutable.ArrayBuffer()), """{"l":null,"a":null}""")
verifyDeser(makeWithRequiredCollectionFields[EmptyIterables],
EmptyIterables(List(), _root_.scala.collection.mutable.ArrayBuffer()), """{"l":null,"a":null}""")