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