cjson是一個(gè)開源的C語(yǔ)言庫(kù),它提供了將JSON轉(zhuǎn)為字符串的功能。使用cjson,我們可以方便地將JSON對(duì)象轉(zhuǎn)為字符串,以方便傳輸或存儲(chǔ)。
例如,我們有以下的JSON對(duì)象: { "name": "Alice", "age": 28, "gender": "female", "hobbies": ["reading", "hiking", "cooking"] } 使用cjson庫(kù),可以實(shí)現(xiàn)將這個(gè)JSON對(duì)象轉(zhuǎn)為字符串的操作。代碼如下: #include#include "cJSON.h" int main() { cJSON *root = cJSON_CreateObject(); cJSON_AddStringToObject(root, "name", "Alice"); cJSON_AddNumberToObject(root, "age", 28); cJSON_AddStringToObject(root, "gender", "female"); cJSON *hobbies = cJSON_CreateArray(); cJSON_AddItemToArray(hobbies, cJSON_CreateString("reading")); cJSON_AddItemToArray(hobbies, cJSON_CreateString("hiking")); cJSON_AddItemToArray(hobbies, cJSON_CreateString("cooking")); cJSON_AddItemToObject(root, "hobbies", hobbies); char *json_str = cJSON_Print(root); printf("%s\n", json_str); cJSON_Delete(root); free(json_str); return 0; } 執(zhí)行以上代碼,輸出的字符串為: { "name": "Alice", "age": 28, "gender": "female", "hobbies": [ "reading", "hiking", "cooking" ] } 這個(gè)字符串即為將JSON對(duì)象轉(zhuǎn)為字符串后的結(jié)果。可以看到,使用cjson庫(kù)非常方便地實(shí)現(xiàn)了JSON對(duì)象和字符串之間的轉(zhuǎn)換。