1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
25 var o
: nullable MyClass
27 redef fun to_s
do return "<MyClass i:{i} s:{s} f:{f} a:[{a.join(", ")}] o:{o or else "<null>"}>"
30 redef class JsonObject
31 redef fun to_s
do return "<JsonObject "+join
(", ", ":")+">"
34 var tests
= new Array[String]
36 # Complete object, as would it be generated by serialization services
38 {"__kind": "obj", "__id": 0, "__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"], "o": null}"""
40 # Skipping the `__kind` and `__id` is allowed
42 {"__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"], "o": null}"""
44 # The attributes can be in any order
46 {"s": "hello", "o": null, "i": 123, "f": 123.456, "__class": "MyClass", "a": ["one", "two"]}"""
48 # Extra attributes are ignored
50 {"__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "o": null, "a": ["one", "two"], "Some random attribute": 777}"""
52 # Skipping `o` will set the attribute to `null`
54 {"__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"]}"""
56 # Nest different classes
58 {"__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"], "o":
59 {"__class": "MyClass", "i": 456, "s": "world", "f": 654.321, "a": ["1", "2"], "o": null}}"""
61 # No `__class` is not advised and will raise an error, but it will be received as a `JsonObject`
63 {"i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"], "o": null}"""
67 {"__class": "MyClass", "i": 123, "s": "hello", "f": 123.456, "a": ["one", "two"], "o": "Not the right type"}"""
69 # Deserializing an invalid JSON string will raise an error
70 tests
.add
"not valid json"
72 # Missing attributes will raise errors and will crash on access
73 #alt2#tests = ["""{"__class": "MyClass", "i": 123, "o": null}"""]
76 var deserializer
= new JsonDeserializer(o
)
77 var deserialized
= deserializer
.deserialize
80 if deserializer
.errors
.not_empty
then print
"# Errors: '{deserializer.errors.join("', '")}'"
81 print
"# Nit: {deserialized or else "null"}\n"