json: support `Byte` in a similar way to `Char`
authorAlexis Laferrière <alexis.laf@xymus.net>
Wed, 26 Jul 2017 12:21:34 +0000 (08:21 -0400)
committerAlexis Laferrière <alexis.laf@xymus.net>
Thu, 10 Aug 2017 16:19:26 +0000 (12:19 -0400)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/json/serialization_read.nit
lib/json/serialization_write.nit
lib/serialization/serialization.nit

index 0ac2bea..3c8b170 100644 (file)
@@ -241,6 +241,17 @@ class JsonDeserializer
                                return val.chars.first
                        end
 
+                       # byte?
+                       if kind == "byte" then
+                               var val = object.get_or_null("__val")
+                               if not val isa Int then
+                                       errors.add new Error("Serialization Error: JSON `byte` object does not declare an integer `__val`.")
+                                       return object
+                               end
+
+                               return val.to_b
+                       end
+
                        errors.add new Error("Deserialization Error: JSON object has an unknown `__kind`.")
                        return object
                end
index 8f3c2d1..009e131 100644 (file)
@@ -33,7 +33,7 @@ class JsonSerializer
        #   be deserialized to their original form using `JsonDeserializer`.
        # * Use references when an object has already been serialized so to not duplicate it.
        # * Support cycles in references.
-       # * Preserve the Nit `Char` type as an object because it does not exist in JSON.
+       # * Preserve the Nit `Char` and `Byte` types as special objects.
        # * The generated JSON is standard and can be read by non-Nit programs.
        #   However, some Nit types are not represented by the simplest possible JSON representation.
        #   With the added metadata, it can be complex to read.
@@ -286,6 +286,19 @@ redef class Char
        end
 end
 
+redef class Byte
+       redef fun accept_json_serializer(v)
+       do
+               if v.plain_json then
+                       to_i.accept_json_serializer v
+               else
+                       v.stream.write "\{\"__kind\": \"byte\", \"__val\": "
+                       to_i.accept_json_serializer v
+                       v.stream.write "\}"
+               end
+       end
+end
+
 redef class CString
        redef fun accept_json_serializer(v) do to_s.accept_json_serializer(v)
 end
index e7f9cf6..fa97009 100644 (file)
@@ -270,6 +270,7 @@ end
 
 redef class Bool super DirectSerializable end
 redef class Char super DirectSerializable end
+redef class Byte super DirectSerializable end
 redef class Int super DirectSerializable end
 redef class Float super DirectSerializable end
 redef class CString super DirectSerializable end