1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Handles serialization and deserialization of objects to/from JSON
21 # `JsonSerializer` write Nit objects that subclass `Serializable` to JSON,
22 # and `JsonDeserializer` can read them. They both use meta-data added to the
23 # generated JSON to recreate the Nit instances with the exact original type.
25 # For more information on Nit serialization, see: ../serialization/README.md
29 # The attribute `JsonSerializer::plain_json` triggers generating plain and
30 # clean JSON. This format is easier to read for an human and a non-Nit program,
31 # but it cannot be fully deserialized. It can still be read by services from
32 # `json::static` and `json::dynamic`.
34 # A shortcut to this service is provided by `Serializable::to_plain_json`.
39 # import json::serialization
45 # var year_of_birth: Int
46 # var next_of_kin: nullable Person
49 # var bob = new Person("Bob", 1986)
50 # var alice = new Person("Alice", 1978, bob)
52 # assert bob.to_plain_json == """
53 # {"name": "Bob", "year_of_birth": 1986, "next_of_kin": null}"""
55 # assert alice.to_plain_json == """
56 # {"name": "Alice", "year_of_birth": 1978, "next_of_kin": {"name": "Bob", "year_of_birth": 1986, "next_of_kin": null}}"""
59 # ## JSON to Nit objects
61 # The `JsonDeserializer` support reading JSON code with minimal meta-data
62 # to easily create Nit object from client-side code or configuration files.
63 # Each JSON object must define the `__class` attribute with the corresponding
64 # Nit class and the expected attributes with its name in Nit followed by its value.
69 # import json::serialization
74 # var description: String
75 # var max_participants: nullable Int
76 # var answers: Array[FlatString]
80 # {"__class": "MeetupConfig", "description": "My Awesome Meetup", "max_participants": null, "answers": ["Pepperoni", "Chicken"]}"""
81 # var deserializer = new JsonDeserializer(json_code)
83 # var meet = deserializer.deserialize
84 # assert meet isa MeetupConfig
85 # assert meet.description == "My Awesome Meetup"
86 # assert meet.max_participants == null
87 # assert meet.answers == ["Pepperoni", "Chicken"]
91 import ::serialization
::caching
92 private import ::serialization
::engine_tools
95 # Serializer of Nit objects to Json string.
97 super CachingSerializer
99 # Target writing stream
102 # Write plain JSON? Standard JSON without metadata for deserialization
104 # If `false`, the default, serialize to support deserialization:
106 # * Write meta-data, including the types of the serialized objects so they can
107 # be deserialized to their original form using `JsonDeserializer`.
108 # * Use references when an object has already been serialized so to not duplicate it.
109 # * Support cycles in references.
110 # * Preserve the Nit `Char` type as an object because it does not exist in JSON.
111 # * The generated JSON is standard and can be read by non-Nit programs.
112 # However, some Nit types are not represented by the simplest possible JSON representation.
113 # With the added meta-data, it can be complex to read.
115 # If `true`, serialize for other programs:
117 # * Nit objects are serialized to pure and standard JSON so they can
118 # be easily read by non-Nit programs and humans.
119 # * Nit objects are serialized for every references, so they can be duplicated.
120 # It is easier to read but it creates a larger output.
121 # * Does not support cycles, will replace the problematic references by `null`.
122 # * Does not serialize the meta-data needed to deserialize the objects
123 # back to regular Nit objects.
124 # * Keys of Nit `HashMap` are converted to their string representation using `to_s`.
125 var plain_json
= false is writable
127 # Write pretty JSON for human eyes?
129 # Toggles skipping lines between attributes of an object and
130 # properly indent the written JSON.
131 var pretty_json
= false is writable
133 # Current indentation level used for writing `pretty_json`
134 private var indent_level
= 0
136 # List of the current open objects, the first is the main target of the serialization
138 # Used only when `plain_json == true` to detect cycles in serialization.
139 private var open_objects
= new Array[Object]
141 # Has the first attribute of the current object already been serialized?
143 # Used only when `plain_json == true`.
144 private var first_attribute
= false
146 redef fun serialize
(object
)
148 if object
== null then
152 for o
in open_objects
do
153 if object
.is_same_serialized
(o
) then
154 # Cycle, can't be managed in plain json
155 warn
"Cycle detected in serialized object, replacing reference with 'null'."
161 open_objects
.add object
164 first_attribute
= true
165 object
.serialize_to_json
self
166 first_attribute
= false
168 if plain_json
then open_objects
.pop
172 redef fun serialize_attribute
(name
, value
)
174 if not plain_json
or not first_attribute
then
176 first_attribute
= false
186 redef fun serialize_reference
(object
)
188 if not plain_json
and cache
.has_object
(object
) then
189 # if already serialized, add local reference
190 var id
= cache
.id_for
(object
)
194 stream
.write
"\"__kind\
": \"ref\
", \"__id\
": "
205 # Write a new line and indent it, only if `pretty_json`
206 private fun new_line_and_indent
210 for i
in indent_level
.times
do stream
.write
"\t"
215 # Deserializer from a Json string.
216 class JsonDeserializer
217 super CachingDeserializer
219 # Json text to deserialize from.
220 private var text
: Text
222 # Root json object parsed from input text.
223 private var root
: nullable Object is noinit
225 # Depth-first path in the serialized object tree.
226 private var path
= new Array[Map[String, nullable Object]]
228 # Last encountered object reference id.
230 # See `id_to_object`.
231 var just_opened_id
: nullable Int = null
234 var root
= text
.parse_json
235 if root
isa Map[String, nullable Object] then path
.add
(root
)
239 redef fun deserialize_attribute
(name
)
241 assert not path
.is_empty
# This is an internal error, abort
242 var current
= path
.last
244 if not current
.keys
.has
(name
) then
245 errors
.add
new Error("Deserialization Error: JSON object has not attribute '{name}'.")
249 var value
= current
[name
]
251 return convert_object
(value
)
254 # This may be called multiple times by the same object from constructors
255 # in different nclassdef
256 redef fun notify_of_creation
(new_object
)
258 var id
= just_opened_id
259 if id
== null then return # Register `new_object` only once
260 cache
[id
] = new_object
263 # Convert from simple Json object to Nit object
264 private fun convert_object
(object
: nullable Object): nullable Object
266 if object
isa JsonParseError then
271 if object
isa Map[String, nullable Object] then
273 if object
.keys
.has
("__kind") then
274 kind
= object
["__kind"]
278 if kind
== "ref" then
279 if not object
.keys
.has
("__id") then
280 errors
.add
new Error("Serialization Error: JSON object reference does not declare a `__id`.")
284 var id
= object
["__id"]
285 if not id
isa Int then
286 errors
.add
new Error("Serialization Error: JSON object reference declares a non-integer `__id`.")
290 if not cache
.has_id
(id
) then
291 errors
.add
new Error("Serialization Error: JSON object reference has an unknown `__id`.")
295 return cache
.object_for
(id
)
299 if kind
== "obj" or kind
== null then
301 if object
.keys
.has
("__id") then
304 if not id
isa Int then
305 errors
.add
new Error("Serialization Error: JSON object declaration declares a non-integer `__id`.")
309 if cache
.has_id
(id
) then
310 errors
.add
new Error("Serialization Error: JSON object with `__id` {id} is deserialized twice.")
315 var class_name
= object
.get_or_null
("__class")
316 if class_name
== null then
317 # Fallback to custom heuristic
318 class_name
= class_name_heuristic
(object
)
321 if class_name
== null then
322 errors
.add
new Error("Serialization Error: JSON object declaration does not declare a `__class`.")
326 if not class_name
isa String then
327 errors
.add
new Error("Serialization Error: JSON object declaration declares a non-string `__class`.")
335 var value
= deserialize_class
(class_name
)
336 just_opened_id
= null
345 if kind
== "char" then
346 if not object
.keys
.has
("__val") then
347 errors
.add
new Error("Serialization Error: JSON `char` object does not declare a `__val`.")
351 var val
= object
["__val"]
353 if not val
isa String or val
.is_empty
then
354 errors
.add
new Error("Serialization Error: JSON `char` object does not declare a single char in `__val`.")
358 return val
.chars
.first
361 errors
.add
new Error("Serialization Error: JSON object has an unknown `__kind`.")
365 # Simple JSON array without serialization metadata
366 if object
isa Array[nullable Object] then
367 var array
= new Array[nullable Object]
368 var types
= new HashSet[String]
369 var has_nullable
= false
371 var res
= convert_object
(e
)
375 types
.add res
.class_name
376 else has_nullable
= true
379 if types
.length
== 1 then
380 var array_type
= types
.first
383 if array_type
== "ASCIIFlatString" or array_type
== "UnicodeFlatString" then
385 typed_array
= new Array[nullable FlatString]
386 else typed_array
= new Array[FlatString]
387 else if array_type
== "Int" then
389 typed_array
= new Array[nullable Int]
390 else typed_array
= new Array[Int]
391 else if array_type
== "Float" then
393 typed_array
= new Array[nullable Float]
394 else typed_array
= new Array[Float]
396 # TODO support all array types when we separate the constructor
397 # `from_deserializer` from the filling of the items.
399 if not has_nullable
then
400 typed_array
= new Array[Object]
402 # Unsupported array type, return as `Array[nullable Object]`
407 assert typed_array
isa Array[nullable Object]
409 # Copy item to the new array
410 for e
in array
do typed_array
.add e
414 # Uninferable type, return as `Array[nullable Object]`
421 redef fun deserialize
424 return convert_object
(root
)
427 # User customizable heuristic to get the name of the Nit class to deserialize `json_object`
429 # This method is called only when deserializing an object without the metadata `__class`.
430 # Return the class name as a `String` when it can be inferred.
431 # Return `null` when the class name cannot be found.
433 # If a valid class name is returned, `json_object` will then be deserialized normally.
434 # So it must contain the attributes of the corresponding class, as usual.
449 # class MyJsonDeserializer
450 # super JsonDeserializer
452 # redef fun class_name_heuristic(json_object)
454 # if json_object.keys.has("error") then return "MyError"
455 # if json_object.keys.has("data") then return "MyData"
460 # var json = """{"data": "some other data"}"""
461 # var deserializer = new MyJsonDeserializer(json)
462 # var deserialized = deserializer.deserialize
463 # assert deserialized isa MyData
465 # json = """{"error": "some error message"}"""
466 # deserializer = new MyJsonDeserializer(json)
467 # deserialized = deserializer.deserialize
468 # assert deserialized isa MyError
470 protected fun class_name_heuristic
(json_object
: Map[String, nullable Object]): nullable String
478 # Deserialize a `nullable Object` from this JSON formatted string
480 # Warning: Deserialization errors are reported with `print_error` and
481 # may be returned as a partial object or as `null`.
483 # This method is not appropriate when errors need to be handled programmatically,
484 # manually use a `JsonDeserializer` in such cases.
485 fun from_json_string
: nullable Object
487 var deserializer
= new JsonDeserializer(self)
488 var res
= deserializer
.deserialize
489 if deserializer
.errors
.not_empty
then
490 print_error
"Deserialization Errors: {deserializer.errors.join(", ")}"
495 redef fun serialize_to_json
(v
) do v
.stream
.write
(to_json
)
498 redef class Serializable
499 private fun serialize_to_json
(v
: JsonSerializer)
501 var id
= v
.cache
.new_id_for
(self)
504 if not v
.plain_json
then
505 v
.new_line_and_indent
506 v
.stream
.write
"\"__kind\
": \"obj\
", \"__id\
": "
507 v
.stream
.write id
.to_s
508 v
.stream
.write
", \"__class\
": \""
509 v.stream.write class_name
515 v
.new_line_and_indent
519 # Serialize this object to a JSON string with metadata for deserialization
520 fun to_json_string
: String
522 var stream
= new StringWriter
523 var serializer
= new JsonSerializer(stream
)
524 serializer
.serialize
self
529 # Serialize this object to plain JSON
531 # This is a shortcut using `JsonSerializer::plain_json`,
532 # see its documentation for more information.
533 fun to_plain_json
: String
535 var stream
= new StringWriter
536 var serializer
= new JsonSerializer(stream
)
537 serializer
.plain_json
= true
538 serializer
.serialize
self
545 redef fun serialize_to_json
(v
) do v
.stream
.write
(to_s
)
549 redef fun serialize_to_json
(v
) do v
.stream
.write
(to_s
)
553 redef fun serialize_to_json
(v
) do v
.stream
.write
(to_s
)
557 redef fun serialize_to_json
(v
)
560 v
.stream
.write to_s
.to_json
562 v
.stream
.write
"\{\"__kind\
": \"char\
", \"__val\
": "
563 v
.stream
.write to_s
.to_json
569 redef class NativeString
570 redef fun serialize_to_json
(v
) do to_s
.serialize_to_json
(v
)
573 redef class Collection[E
]
574 # Utility to serialize a normal Json array
575 private fun serialize_to_pure_json
(v
: JsonSerializer)
583 else v
.stream
.write
","
584 v
.new_line_and_indent
586 if not v
.try_to_serialize
(e
) then
587 assert e
!= null # null would have been serialized
588 v
.warn
("element of type {e.class_name} is not serializable.")
592 v
.new_line_and_indent
597 redef class SimpleCollection[E
]
598 redef fun serialize_to_json
(v
)
600 # Register as pseudo object
601 if not v
.plain_json
then
602 var id
= v
.cache
.new_id_for
(self)
603 v
.stream
.write
"""{"""
605 v
.new_line_and_indent
606 v
.stream
.write
""""__kind": "obj", "__id": """
607 v
.stream
.write id
.to_s
608 v
.stream
.write
""", "__class": """"
609 v.stream.write class_name
610 v.stream.write """","""
611 v.new_line_and_indent
612 v.stream.write """"__items": """
615 serialize_to_pure_json v
617 if not v.plain_json then
619 v.new_line_and_indent
624 redef init from_deserializer(v)
627 if v isa JsonDeserializer then
628 v.notify_of_creation self
631 var arr = v.path.last["__items"].as(SequenceRead[nullable Object])
633 var obj = v.convert_object(o)
640 redef class Map[K, V]
641 redef fun serialize_to_json(v)
643 # Register as pseudo object
644 var id = v.cache.new_id_for(self)
650 for key, val in self do
654 v.new_line_and_indent
656 var k = key or else "null"
657 v.stream.write k.to_s.to_json
659 if not v.try_to_serialize(val) then
660 assert val != null # null would have been serialized
661 v.warn("element of type {val.class_name} is not serializable.")
662 v.stream.write "null"
666 v.new_line_and_indent
671 v.new_line_and_indent
672 v.stream.write """"__kind": "obj", "__id": """
673 v.stream.write id.to_s
674 v.stream.write """, "__class": """"
675 v.stream.write class_name
676 v.stream.write """", "__length
": """
677 v.stream.write length.to_s
680 v.new_line_and_indent
681 v.stream.write """"__keys
": """
682 keys.serialize_to_pure_json v
685 v.new_line_and_indent
686 v.stream.write """"__values
": """
687 values.serialize_to_pure_json v
690 v.new_line_and_indent
695 redef init from_deserializer(v)
699 if v isa JsonDeserializer then
700 v.notify_of_creation self
703 var length = v.deserialize_attribute("__length
").as(Int)
704 var keys = v.path.last["__keys
"].as(SequenceRead[nullable Object])
705 var values = v.path.last["__values
"].as(SequenceRead[nullable Object])
706 for i in length.times do
707 var key = v.convert_object(keys[i])
708 var value = v.convert_object(values[i])