lib/simple_json_reader: unprotect special char in strings
[nit.git] / tests / test_deserialization.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 import serialization
18 import json_serialization
19
20 # Simple class
21 class A
22 auto_serializable
23 super Serializable
24
25 var b: Bool
26 var f: Float
27 var i: Int
28 var s: String
29 var n: nullable Int
30
31 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int)
32 do
33 self.b = b
34 self.f = f
35 self.i = i
36 self.s = s
37 end
38
39 redef fun to_s do return "<A: {b} {f} {i} {s} {n != null}>"
40 end
41
42 # Sub-class of A
43 class B
44 auto_serializable
45 super A
46
47 var ii: Int
48 var ss: String
49
50 init(b: Bool, c: Char, f: Float, i: Int, s: String, n: nullable Int, ii: Int, ss: String)
51 do
52 super(b, c, f, i, s, n)
53
54 self.ii = ii
55 self.ss = ss
56 end
57
58 redef fun to_s do return "<B: {super} {ii} {ss}>"
59 end
60
61 # Composed of an A and a B
62 class C
63 auto_serializable
64 super Serializable
65
66 var a: A
67 var b: B
68 var aa: A
69
70 init(a: A, b: B)
71 do
72 self.a = a
73 self.b = b
74 self.aa = a
75 end
76
77 redef fun to_s do return "<C: {a} {b}>"
78 end
79
80 # Class with cyclic reference
81 class D
82 auto_serializable
83 super B
84
85 var d: nullable D = null
86
87 redef fun to_s do return "<D: {super} {d != null}>"
88 end
89
90 var a = new A(true, 'a', 0.1234, 1234, "asdf", null)
91 var b = new B(false, 'b', 123.123, 2345, "hjkl", 12, 1111, "qwer")
92 var c = new C(a, b)
93 var d = new D(false, 'b', 123.123, 2345, "new line ->\n<-", null, 1111, "\t\f\"\r\\/")
94 d.d = d
95
96 for o in new Array[nullable Serializable].with_items(a, b, c, d) do
97 var stream = new StringOStream
98 var serializer = new JsonSerializer(stream)
99 serializer.serialize(o)
100
101 var deserializer = new JsonDeserializer(stream.to_s)
102 var deserialized = deserializer.deserialize
103
104 print "# Nit:\n{o}\n"
105 print "# Json:\n{stream}\n"
106 print "# Back in Nit:\n{deserialized}\n"
107 end