test_set_serializer.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <assert.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include "json.h"
  5. #include "printbuf.h"
  6. struct myinfo {
  7. int value;
  8. };
  9. static int freeit_was_called = 0;
  10. static void freeit(json_object *jso, void *userdata)
  11. {
  12. struct myinfo *info = userdata;
  13. printf("freeit, value=%d\n", info->value);
  14. // Don't actually free anything here, the userdata is stack allocated.
  15. freeit_was_called = 1;
  16. }
  17. static int custom_serializer(struct json_object *o,
  18. struct printbuf *pb,
  19. int level,
  20. int flags)
  21. {
  22. sprintbuf(pb, "Custom Output");
  23. return 0;
  24. }
  25. int main(int argc, char **argv)
  26. {
  27. json_object *my_object;
  28. MC_SET_DEBUG(1);
  29. printf("Test setting, then resetting a custom serializer:\n");
  30. my_object = json_object_new_object();
  31. json_object_object_add(my_object, "abc", json_object_new_int(12));
  32. json_object_object_add(my_object, "foo", json_object_new_string("bar"));
  33. printf("my_object.to_string(standard)=%s\n", json_object_to_json_string(my_object));
  34. struct myinfo userdata = { .value = 123 };
  35. json_object_set_serializer(my_object, custom_serializer, &userdata, freeit);
  36. printf("my_object.to_string(custom serializer)=%s\n", json_object_to_json_string(my_object));
  37. printf("Next line of output should be from the custom freeit function:\n");
  38. freeit_was_called = 0;
  39. json_object_set_serializer(my_object, NULL, NULL, NULL);
  40. assert(freeit_was_called);
  41. printf("my_object.to_string(standard)=%s\n", json_object_to_json_string(my_object));
  42. json_object_put(my_object);
  43. // ============================================
  44. my_object = json_object_new_object();
  45. printf("Check that the custom serializer isn't free'd until the last json_object_put:\n");
  46. json_object_set_serializer(my_object, custom_serializer, &userdata, freeit);
  47. json_object_get(my_object);
  48. json_object_put(my_object);
  49. printf("my_object.to_string(custom serializer)=%s\n", json_object_to_json_string(my_object));
  50. printf("Next line of output should be from the custom freeit function:\n");
  51. freeit_was_called = 0;
  52. json_object_put(my_object);
  53. assert(freeit_was_called);
  54. return 0;
  55. }