C語言是一門面向過程的編程語言,通常被用來編寫系統(tǒng)軟件。在C語言中,如何調(diào)用API接口并解析返回的JSON格式數(shù)據(jù)呢?下面我們通過一個(gè)小例子來講解。
#include <stdio.h> #include <stdlib.h> #include <curl/curl.h> #include <jansson.h> struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { printf("Not enough memory (realloc returned NULL)\n"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main(void) { CURL *curl; CURLcode res; struct MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "https://api.github.com/users/github"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk); res = curl_easy_perform(curl); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { printf("%lu bytes retrieved\n", (unsigned long)chunk.size); json_error_t error; json_t *root; root = json_loads(chunk.memory, 0, &error); if (!root) { printf("error: on line %d: %s\n", error.line, error.text); return 1; } const char *name; json_unpack(root, "{s:s}", "name", &name); printf("name: %s\n", name); json_decref(root); } curl_easy_cleanup(curl); } free(chunk.memory); return 0; }
在代碼中,我們使用curl庫實(shí)現(xiàn)HTTP請(qǐng)求,并將返回的數(shù)據(jù)保存到內(nèi)存中。然后,我們使用jansson庫解析JSON數(shù)據(jù),并提取出name屬性的值。
以上就是通過C語言調(diào)用API接口并解析JSON數(shù)據(jù)的示例。希望這樣的例子能夠幫助您更好地理解C語言的相關(guān)知識(shí)。