C語言是一門非常重要的編程語言,它可以編寫網絡程序,通過網絡訪問來獲取JSON數據。實現網絡請求,需要使用對應的網絡庫,在C語言中最常用的網絡庫是libcurl。此外,還需要解析JSON數據,C語言中最常用的JSON解析庫是cJSON。
#include#include #include #include #include "cJSON.h" typedef struct MemoryStruct { char *memory; size_t size; } MemoryStruct; static size_t WriteMemoryCallback(char *ptr, size_t size, size_t nmemb, void *userdata) { size_t realsize = size * nmemb; MemoryStruct *mem = (MemoryStruct *)userdata; char *temp = realloc(mem->memory, mem->size + realsize + 1); if (temp == NULL) { printf("Not enough memory (realloc returned NULL)\n"); return 0; } mem->memory = temp; memcpy(&(mem->memory[mem->size]), ptr, realsize); mem->size += realsize; mem->memory[mem->size] = '\0'; return realsize; } int main() { CURL *curl; CURLcode res; MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl_global_init(CURL_GLOBAL_ALL); curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://example.com/api.json"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl); if (res != CURLE_OK) { printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { cJSON *json = cJSON_Parse(chunk.memory); printf("JSON result:\n%s\n", cJSON_Print(json)); cJSON_Delete(json); } curl_easy_cleanup(curl); } free(chunk.memory); curl_global_cleanup(); return 0; }
在上述代碼中,我們首先定義了一個“記憶體結構體”,它用于存儲從網絡中獲取到的JSON數據。然后,我們使用libcurl庫中的“easy”接口來實現GET請求,將獲取到的數據存儲到“記憶體結構體”中。最后,我們使用cJSON庫來解析JSON數據,并將其打印出來。