#include #include #include #include static FILE* tmp = nullptr; static char buffer[1024]; static Json json; void setUp() { tmp = tmpfile(); TEST_ASSERT_NOT_NULL(tmp); json = json_init(tmp, INDENT_TAB); } void tearDown() { json_free(&json); if (tmp) { fclose(tmp); tmp = nullptr; } } struct Person { const char* name; int age; }; void serialize_person(Json* json, const struct Person* person) { json_begin_object(json); { json_add_object_field(json, "name"); json_add_string(json, person->name); json_add_object_field(json, "age"); json_add_long(json, person->age); } json_end_object(json); } struct Status { const char* description; bool is_success; }; void serialize_status(Json* json, const struct Status* status) { json_begin_object(json); { json_add_object_field(json, "description"); json_add_string(json, status->description); json_add_object_field(json, "is_success"); json_add_bool(json, status->is_success); } json_end_object(json); } struct PersonsResult { struct Status status; int length; struct Person* persons; }; void test_json_complex() { struct Person persons[4] = { { .name = "Alice", .age = 35 }, { .name = "Bob", .age = 67 }, { .name = "Patricia", .age = 54 }, { .name = "Jake", .age = 16 }, }; struct PersonsResult persons_result = { .status = { .description = "ok", .is_success = true }, .length = sizeof(persons) / sizeof(struct Person), .persons = persons, }; json_begin_object(&json); { json_add_object_field(&json, "status"); serialize_status(&json, &persons_result.status); json_add_object_field(&json, "length"); json_add_long(&json, persons_result.length); json_add_object_field(&json, "persons"); json_begin_array(&json); { for (auto i = 0; i < persons_result.length; ++i) { auto person = persons_result.persons[i]; serialize_person(&json, &person); } } json_end_array(&json); } json_end_object(&json); fflush(tmp); rewind(tmp); auto n = fread(buffer, 1, sizeof(buffer) - 1, tmp); buffer[n] = '\0'; TEST_ASSERT_EQUAL_STRING("{\n\t\"status\": {\n\t\t\"description\": \"ok\",\n\t\t\"is_success\": true\n\t},\n\t\"length\": 4,\n\t\"persons\": [\n\t\t{\n\t\t\t\"name\": \"Alice\",\n\t\t\t\"age\": 35\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Bob\",\n\t\t\t\"age\": 67\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Patricia\",\n\t\t\t\"age\": 54\n\t\t},\n\t\t{\n\t\t\t\"name\": \"Jake\",\n\t\t\t\"age\": 16\n\t\t}\n\t]\n}", buffer); } int main() { UNITY_BEGIN(); { RUN_TEST(test_json_complex); } return UNITY_END(); }