lib/json: intro simple services for scripts and the like
authorAlexis Laferrière <alexis.laf@xymus.net>
Wed, 28 Oct 2015 12:43:53 +0000 (08:43 -0400)
committerAlexis Laferrière <alexis.laf@xymus.net>
Sun, 8 Nov 2015 17:50:57 +0000 (12:50 -0500)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/json/serialization.nit

index 5c3b896..ad44406 100644 (file)
@@ -448,6 +448,26 @@ class JsonDeserializer
        end
 end
 
+redef class Text
+
+       # Deserialize a `nullable Object` from this JSON formatted string
+       #
+       # Warning: Deserialization errors are reported with `print_error` and
+       # may be returned as a partial object or as `null`.
+       #
+       # This method is not appropriate when errors need to be handled programmatically,
+       # manually use a `JsonDeserializer` in such cases.
+       fun from_json_string: nullable Object
+       do
+               var deserializer = new JsonDeserializer(self)
+               var res = deserializer.deserialize
+               if deserializer.errors.not_empty then
+                       print_error "Deserialization Errors: {deserializer.errors.join(", ")}"
+               end
+               return res
+       end
+end
+
 redef class Serializable
        private fun serialize_to_json(v: JsonSerializer)
        do
@@ -464,6 +484,16 @@ redef class Serializable
                v.stream.write "\}"
        end
 
+       # Serialize this object to a JSON string with metadata for deserialization
+       fun to_json_string: String
+       do
+               var stream = new StringWriter
+               var serializer = new JsonSerializer(stream)
+               serializer.serialize self
+               stream.close
+               return stream.to_s
+       end
+
        # Serialize this object to plain JSON
        #
        # This is a shortcut using `JsonSerializer::plain_json`,