在C語言中,獲取JSON數據是一項常見的任務。雖然C語言并沒有內置的JSON解析庫,但我們可以使用C POST方法來獲取JSON數據。下面是一個獲取JSON數據的代碼示例:
#include <stdlib.h> #include <stdio.h> #include <curl/curl.h> typedef struct { char *data; size_t size; } MemoryStruct; static size_t writeMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; MemoryStruct *mem = (MemoryStruct *) userp; char *ptr = realloc(mem->data, mem->size + realsize + 1); if (ptr == NULL) { printf("not enough memory\n"); return 0; } mem->data = ptr; memcpy(&(mem->data[mem->size]), contents, realsize); mem->size += realsize; mem->data[mem->size] = 0; return realsize; } int main(int argc, char **argv) { CURL *curl; CURLcode res; MemoryStruct chunk; chunk.data = (char *) 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/getjsondata"); 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 { printf("%lu bytes retrieved\n", (long) chunk.size); printf("JSON data: %s\n", chunk.data); } curl_easy_cleanup(curl); } free(chunk.data); curl_global_cleanup(); return 0; }
在這個代碼中,我們使用了CURL庫來處理HTTP請求和響應,通過POST請求獲取了JSON數據。在main函數中,我們定義了一個MemoryStruct結構體來存放獲取到的JSON數據,通過writeMemoryCallback函數來將數據寫入到MemoryStruct中。最后,我們使用curl_easy_perform函數來執行HTTP請求并獲取響應數據,通過chunk.data輸出JSON數據。
下一篇vue 2.4