Json.vala 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using Invercargill;
  2. using Invercargill.DataStructures;
  3. using InvercargillJson;
  4. using Statum;
  5. namespace ClankerSaddle {
  6. /**
  7. * Helpers for shaping Statum slot state. Because Statum's GObjectMapping
  8. * cannot serialise array/list fields, lists are built as a JsonArray and set
  9. * on a PropertyDictionary under a key, where stm-for-{x}-in can iterate them.
  10. */
  11. public class StateJson : Object {
  12. /**
  13. * Builds a JSON array element from a lot of GObject row models, mapping
  14. * each row via GObjectMapping. Use the result as a slot public-data value:
  15. * `dict["tasks"] = StateJson.list<TaskView>(rows);`
  16. */
  17. public static JsonElement list<T>(Lot<T> items) throws GLib.Error {
  18. var arr = new JsonArray();
  19. foreach (var item in items) {
  20. var props = GObjectMapping.to_properties((Object) item);
  21. arr.add(new JsonElement.from_properties(props));
  22. }
  23. return new JsonElement.from_elements(arr);
  24. }
  25. /** Same as {@link list} but accepts a Vala array. */
  26. public static JsonElement list_array<T>(T[] items) throws GLib.Error {
  27. var arr = new JsonArray();
  28. foreach (var item in items) {
  29. var props = GObjectMapping.to_properties((Object) item);
  30. arr.add(new JsonElement.from_properties(props));
  31. }
  32. return new JsonElement.from_elements(arr);
  33. }
  34. }
  35. }