# See the License for the specific language governing permissions and
# limitations under the License.
+# Handles serialization and deserialization of objects to/from Json.
module json_serialization
import serialization
import json::static
+# Serializer of Nit objects to Json string.
class JsonSerializer
super Serializer
# Target writing stream
var stream: OStream
- init(stream: OStream) do self.stream = stream
-
redef fun serialize(object)
do
if object == null then
end
end
- # Map of references to already serialized objects
+ # Map of references to already serialized objects.
var refs_map = new HashMap[Serializable,Int]
+ # Get the internal serialized reference for this `object`.
private fun ref_id_for(object: Serializable): Int
do
if refs_map.keys.has(object) then
end
end
-# Deserializer from a Json string
+# Deserializer from a Json string.
class JsonDeserializer
super Deserializer
- var root: nullable Jsonable
+ # Json text to deserialize from.
+ private var text: Text
+
+ # Root json object parsed from input text.
+ var root: nullable Jsonable is noinit
+
+ # Depth-first path in the serialized object tree.
var path = new Array[JsonObject]
+
+ # Map of refenrences to already deserialized objects.
var id_to_object = new HashMap[Int, Object]
+ # Last encountered object reference id.
+ #
+ # See `id_to_object`.
var just_opened_id: nullable Int = null
- init(text: Text)
- do
+ init do
var root = text.parse_json
if root isa JsonObject then path.add(root)
self.root = root
end
redef class Char
- redef fun serialize_to_json(v) do v.stream.write "\{\"__kind\": \"char\", \"__val\": \"{to_s.to_json_s}\"\}"
+ redef fun serialize_to_json(v) do v.stream.write "\{\"__kind\": \"char\", \"__val\": {to_s.to_json}\}"
end
redef class String
- redef fun serialize_to_json(v) do v.stream.write("\"{to_json_s}\"")
-
- private fun to_json_s: String do return self.replace("\\", "\\\\").
- replace("\"", "\\\"").replace("/", "\\/").
- replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
- # FIXME add support for unicode char when supported by Nit strings
- # FIXME add support for \f! # .replace("\f", "\\f")
- # FIXME add support for \b .replace("\b", "\\b")
+ redef fun serialize_to_json(v) do v.stream.write(to_json)
end
redef class NativeString
end
end
+ # Instanciate a new `Array` from its serialized representation.
init from_deserializer(v: Deserializer)
do
if v isa JsonDeserializer then