You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

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