int TestSomeFuncs() { int score = 10; // 调用同学们实现的接口 JSON *root = CreateObject(); // 评测1 是否能正确创建Object if (root->type != JSON_OBJECT) { // 类型不对 score -= 2; } AddItemToObject(root, "name", CreateString("Hello World")); // 评测2 是否能正确AddItemToObject并且读取 JSON *value = GetItemInObject(root, "name"); // 类型不对或者值不对 if (value->type != JSON_STRING || strcmp(value->valuestring, "Hello World")) { score -= 2; } JSON *array = CreateArray(); AddItemToArray(array, CreateBool(0)); AddItemToArray(array, CreateNumber(2.3)); // 评测3 是否能正确AddItemToArray并且读取 JSON *item = GetItemInArray(array, 1); if (item->type != JSON_NUMBER || item->valuedouble != 2.3) { score -= 2; } AddItemToObject(root, "array", courses); // 现在root的状态 /* { "name": "Hello Wrold", "array": [ false, 2.3 ] } */ // 评测4 是否能正确地根据路径读取值 item = GetItemInJSON(root, "/array/0"); if (item->type != JSON_FALSE) { score -= 2; } PrintJSONToFile(root, "test.json"); // 评测5 是否与标准答案文件相同 if (!IsSame("test.json", "test.json.ans")) { score -= 2; } return score; }
JSON* GetItemInJSON(JSON *json, const char *path) { JSON *rtn = NULL; JSON *next_json = NULL; if (path[0] != '/') { printf("Exception: Invalid path format.\n"); return NULL; } if (strcmp("/", path) == 0) { return json; } char *sub_s = GetSubString(path, 1, strlen(path) - 1); char *next_slash = strchr(sub_s, '/'); if (next_slash == NULL) { switch (json->type) { case JSON_ARRAY: rtn = GetItemInArray(json, atoi(sub_s)); break; case JSON_OBJECT: rtn = GetItemInObject(json, sub_s); break; } free(sub_s); return rtn; } else { char *search_item_key = GetSubString(sub_s, 0, next_slash - sub_s); char *search_item_path = GetSubString(next_slash, 0, strlen(next_slash)); switch (json->type) { case JSON_ARRAY: next_json = GetItemInArray(json, atoi(search_item_key)); case JSON_OBJECT: next_json = GetItemInObject(json, search_item_key); } rtn = GetItemInJSON(next_json, search_item_path); free(search_item_key); free(search_item_path); free(sub_s); return rtn; } return NULL; }