C语言借助cJSON生成和解析json数据
作者:互联网
一、下载cJSON
下载地址:https://github.com/DaveGamble/cJSON
二、
int main(void)
{
//先创建空对象
cJSON *json = cJSON_CreateObject();
//添加数组
cJSON *array = NULL;
cJSON_AddItemToObject(json, "getDataFromHandler", array = cJSON_CreateArray());
//在数组上添加对象
cJSON *obj = NULL;
cJSON_AddItemToArray(array, obj = cJSON_CreateObject());
cJSON_AddItemToObject(obj, "user", cJSON_CreateString("robot"));
cJSON_AddStringToObject(obj, "opinion", "adopt");
//在对象上添加键值对
cJSON_AddItemToArray(array, obj = cJSON_CreateObject());
cJSON_AddItemToObject(obj, "user", cJSON_CreateString("infodba"));
cJSON_AddItemToObject(obj, "opinion", cJSON_CreateString("adopt"));
cJSON_AddItemToArray(array, obj = cJSON_CreateObject());
cJSON_AddStringToObject(obj, "user", "test");
cJSON_AddStringToObject(obj, "opinion", "adopt");
//生成json文件
FILE *fp = fopen("create.json", "w");
char *buf = cJSON_Print(json);
printf("%s\n", buf);
fwrite(buf, strlen(buf), 1, fp);
fclose(fp);
testJSONSend(buf);
/*test1();*/
//清理工作
cJSON_Delete(json);
return 0;
}
标签:obj,cJSON,CreateObject,C语言,json,array,buf 来源: https://blog.csdn.net/weixin_45084986/article/details/121382751