Last active
March 14, 2021 11:29
-
-
Save kosmolot/0aeb88d259055b388b50e4054392797b to your computer and use it in GitHub Desktop.
Vala partial serialization (using json-glib)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* An example of serialization. | |
* This example serializes and deserializes only 'x' property. | |
* | |
* vala: 0.36.3 | |
* json-glib: 1.3.2 | |
*/ | |
public class Point : GLib.Object, Json.Serializable { | |
public int x { get; set; } | |
public int y { get; set; } | |
public unowned ParamSpec? find_property (string name) { | |
return get_class().find_property(name); | |
} | |
public bool deserialize_property (string property_name, out Value value, ParamSpec pspec, Json.Node property_node) { | |
switch (property_name) { | |
case "x": | |
value = Value(typeof(int)); | |
value.set_int((int) property_node.get_int()); | |
return true; | |
default: | |
return false; | |
} | |
} | |
public Json.Node serialize_property (string property_name, Value value, ParamSpec pspec) { | |
switch (property_name) { | |
case "x": | |
return default_serialize_property(property_name, value, pspec); | |
default: | |
return null; | |
} | |
} | |
} | |
void main () { | |
Point p = new Point(); | |
p.x = 123; | |
p.y = 456; | |
print("- original: (%d, %d)\n", p.x, p.y); | |
Json.Node root = Json.gobject_serialize(p); | |
Json.Generator gen = new Json.Generator(); | |
gen.set_root(root); | |
string data = gen.to_data(null); | |
print("- serialized: %s\n", data); | |
Object obj = Json.gobject_deserialize(typeof(Point), root); | |
p = (Point) obj; | |
print("- deserialized: (%d, %d)\n", p.x, p.y); | |
} | |
/* Output: | |
* - original: (123, 456) | |
* - serialized: {"x":123} | |
* - deserialized: (123, 0) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment