C語(yǔ)言中,要通過(guò)JSON獲取數(shù)組,需要用到一個(gè)開源庫(kù)——json-c。這個(gè)庫(kù)提供了許多函數(shù),用于解析JSON數(shù)據(jù),并且能夠靈活、高效地處理數(shù)組。
#include <stdio.h> #include <json-c/json.h> int main() { const char* json_string = "{\"name\": \"Tina\", \"age\": 20, \"hobbies\": [\"reading\", \"singing\", \"dancing\"]}"; struct json_object* json_object = json_tokener_parse(json_string); struct json_object* hobbies_object = NULL; if (json_object_object_get_ex(json_object, "hobbies", &hobbies_object)) { if (json_object_is_type(hobbies_object, json_type_array)) { int hobbies_count = json_object_array_length(hobbies_object); printf("Tina has %d hobbies:\n", hobbies_count); for (int i = 0; i < hobbies_count; i++) { struct json_object* hobby_object = json_object_array_get_idx(hobbies_object, i); printf("%d: %s\n", i + 1, json_object_get_string(hobby_object)); } } else { printf("Hobbies is not an array!\n"); } } else { printf("Cannot find key 'hobbies' in JSON data!\n"); } json_object_put(json_object); return 0; }
上面這段代碼演示了如何獲取JSON數(shù)據(jù)中的
hobbies
數(shù)組。首先,需要將JSON字符串解析成JSON對(duì)象,使用json_tokener_parse
函數(shù)就可以實(shí)現(xiàn)。接下來(lái),通過(guò)json_object_object_get_ex
函數(shù)獲取到hobbies
對(duì)象,再用json_object_is_type
函數(shù)判斷是否為數(shù)組類型,如果是,就可以計(jì)算數(shù)組長(zhǎng)度,并且通過(guò)json_object_array_get_idx
函數(shù)訪問(wèn)數(shù)組元素。最后,記得釋放JSON對(duì)象的內(nèi)存,調(diào)用json_object_put
函數(shù)即可。