Merge: doc: fixed some typos and other misc. corrections
[nit.git] / tests / test_json_deserialization_heuristic.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
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
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import json
16 import json::static
17
18 class MyData
19 serialize
20
21 var data: String
22
23 redef fun to_s do return "<MyData {data}>"
24 end
25
26 class MyError
27 serialize
28
29 var error: String
30
31 redef fun to_s do return "<MyError {error}>"
32 end
33
34 class MyJsonDeserializer
35 super JsonDeserializer
36
37 redef fun class_name_heuristic(json_object)
38 do
39 if json_object.keys.has("error") then return "MyError"
40 if json_object.keys.has("data") then return "MyData"
41 return null
42 end
43 end
44
45 var tests = new Array[String]
46
47 # Object with meta data, does not need the heuristic
48 tests.add """
49 {"__class": "MyData", "data": "some data"}"""
50
51 # Objects without meta data
52 tests.add """
53 {"data": "some other data"}"""
54 tests.add """
55 {"error": "some error message"}"""
56
57 for o in tests do
58 var deserializer = new MyJsonDeserializer(o)
59 var deserialized = deserializer.deserialize
60
61 print "# JSON: {o}"
62 if deserializer.errors.not_empty then print "# Errors: '{deserializer.errors.join("', '")}'"
63 print "# Nit: {deserialized or else "null"}\n"
64 end