Json.vala 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. * A JSON array of plain strings (e.g. a block's multiple-choice
  36. * options).
  37. */
  38. public static JsonElement strings(string[] values) throws GLib.Error {
  39. var arr = new JsonArray();
  40. foreach (var value in values) {
  41. arr.add(new JsonElement.from_element(new NativeElement<string>(value)));
  42. }
  43. return new JsonElement.from_elements(arr);
  44. }
  45. /**
  46. * Per-row enrichment hook for {@link list_rich}: after each item
  47. * is mapped, the enricher may add array/complex values the plain
  48. * GObject mapping cannot serialise (e.g. a block's option list).
  49. */
  50. public delegate void PropertyEnricher(Object item, PropertyDictionary props) throws GLib.Error;
  51. /**
  52. * Like {@link list}, but every row's property dictionary passes
  53. * through `enrich` before serialisation so callers can attach
  54. * fields GObjectMapping drops (arrays, nested objects).
  55. */
  56. public static JsonElement list_rich<T>(Lot<T> items, owned PropertyEnricher enrich) throws GLib.Error {
  57. var arr = new JsonArray();
  58. foreach (var item in items) {
  59. var props = (PropertyDictionary) GObjectMapping.to_properties((Object) item);
  60. enrich((Object) item, props);
  61. arr.add(new JsonElement.from_properties(props));
  62. }
  63. return new JsonElement.from_elements(arr);
  64. }
  65. }
  66. }