Skip to content

Instantly share code, notes, and snippets.

@gffranco
Forked from kosmolot/serialization.vala
Created April 24, 2019 16:57
Show Gist options
  • Save gffranco/8274646803ef36a39b6d9a76af280593 to your computer and use it in GitHub Desktop.
Save gffranco/8274646803ef36a39b6d9a76af280593 to your computer and use it in GitHub Desktop.
Vala partial serialization (using json-glib)
/*
* 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