現在,越來越多的網絡應用程序需要與服務器端進行交互。而JSON(JavaScript Object Notation)被廣泛應用于這種交互方式中。
C JSON是一種用于解析和生成JSON數據的C語言庫。它的基本結構如下:
typedef struct json_object_struct { enum json_type o_type; union data { struct array_list* array; struct lh_table* object; char* string; double dbl; int64_t int64; uint64_t uint64; int boolean; } o; } json_object;
通過使用C JSON,我們可以通過HTTP請求向服務器端發送JSON數據,并且解析服務器端返回的JSON數據。具體代碼實現如下:
#include "json.h" #include#include static size_t WriteMemoryCallback(void* contents, size_t size, size_t nmemb, void* userp) { size_t realsize = size * nmemb; char* ptr = realloc(userp, strlen(userp) + realsize + 1); if (ptr == NULL) { printf("Not enough memory\n"); return 0; } memcpy(ptr + strlen(ptr), contents, realsize); *(ptr + strlen(ptr) + realsize) = '\0'; return realsize; } int main(void) { CURL* curl_handle; CURLcode res; char* read_data = (char*)malloc(1); *read_data = '\0'; json_object* read_obj; char* post_data = "{ \ \"name\": \"John Smith\", \ \"age\": 25, \ \"address\": \"Los Angeles, CA 90001\" \ }"; curl_global_init(CURL_GLOBAL_DEFAULT); curl_handle = curl_easy_init(); if (curl_handle) { curl_easy_setopt(curl_handle, CURLOPT_URL, "http://example.com"); curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, post_data); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void*)read_data); res = curl_easy_perform(curl_handle); if (res != CURLE_OK) { fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); } else { read_obj = json_tokener_parse(read_data); printf("name: %s\n", json_object_get_string(json_object_object_get(read_obj, "name"))); printf("age: %d\n", json_object_get_int(json_object_object_get(read_obj, "age"))); printf("address: %s\n", json_object_get_string(json_object_object_get(read_obj, "address"))); } curl_easy_cleanup(curl_handle); } curl_global_cleanup(); return 0; }
上面的代碼首先使用cURL庫向服務器端發送HTTP請求,將post_data作為數據發送。同時,將服務器響應的數據通過WriteMemoryCallback函數寫入read_data中,最后使用json_tokener_parse函數解析read_data,獲取服務器返回的JSON數據。在這里,我們以"name"、"age"、"address"三個字段的值作為樣例進行解析,并打印出來。