JSON(JavaScript Object Notation)是一種輕量級(jí)的數(shù)據(jù)交換格式,在web應(yīng)用程序中,常用于傳輸數(shù)據(jù)。C語(yǔ)言使用第三方庫(kù)cJSON,能夠很方便地生成JSON格式的字符串或文件。
以下是一個(gè)簡(jiǎn)單的例子,演示如何生成JSON格式文件:
#include "cJSON.h" #include <stdio.h> int main() { cJSON* root = cJSON_CreateObject(); cJSON_AddItemToObject(root, "name", cJSON_CreateString("Lucy")); cJSON_AddItemToObject(root, "age", cJSON_CreateNumber(18)); cJSON_AddItemToObject(root, "hobby", cJSON_CreateStringArray( (const char*[]){"reading", "listening to music"}, 2 )); cJSON_AddItemToObject(root, "address", cJSON_CreateObject()); cJSON_AddItemToObject(root->child, "province", cJSON_CreateString("Guangdong")); cJSON_AddItemToObject(root->child, "city", cJSON_CreateString("Shenzhen")); cJSON_AddItemToObject(root->child, "postcode", cJSON_CreateString("518000")); char* jsonStr = cJSON_Print(root); FILE* fp = fopen("example.json", "w"); fprintf(fp, "%s", jsonStr); fclose(fp); cJSON_Delete(root); return 0; }
上述代碼使用cJSON庫(kù)的API,創(chuàng)建了一個(gè)JSON對(duì)象,并使用`cJSON_AddItemToObject`函數(shù),添加了name、age、hobby、address四個(gè)字段。其中,hobby是一個(gè)字符串?dāng)?shù)組,address是一個(gè)嵌套的對(duì)象。最后,使用`cJSON_Print`函數(shù),將JSON對(duì)象轉(zhuǎn)換成字符串,并存儲(chǔ)到文件example.json中。
執(zhí)行上述代碼,生成的example.json文件內(nèi)容如下:
{ "name": "Lucy", "age": 18, "hobby": [ "reading", "listening to music" ], "address": { "province": "Guangdong", "city": "Shenzhen", "postcode": "518000" } }
可以看到,生成的JSON格式文件與代碼中創(chuàng)建的JSON對(duì)象結(jié)構(gòu)一致。