拷备.c和.h文件到指定的目录中
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include "cJSON.h"
int main(int argc, char *argv[])
{
// 创建对象
cJSON* obj = cJSON_CreateObject();
// 创建子对象
cJSON* subObj = cJSON_CreateObject();
// 添加key-value
cJSON_AddItemToObject(subObj,"factory",cJSON_CreateString("一汽大众"));
cJSON_AddItemToObject(subObj,"last",cJSON_CreateNumber(31));
cJSON_AddItemToObject(subObj,"price",cJSON_CreateNumber(83));
cJSON_AddItemToObject(subObj,"sell",cJSON_CreateNumber(49));
cJSON_AddItemToObject(subObj,"sum",cJSON_CreateNumber(80));
// 创建数组
cJSON* array = cJSON_CreateArray();
cJSON_AddItemToArray(array,cJSON_CreateNumber(123));
cJSON_AddItemToArray(array,cJSON_CreateNumber(1));
cJSON_AddItemToArray(array,cJSON_CreateString("hello,world"));
// 创建对象
cJSON* childObj = cJSON_CreateObject();
cJSON_AddItemToObject(childObj,"梅塞奔驰",cJSON_CreateString("心所向,持以恒"));
cJSON_AddItemToArray(array,childObj);
cJSON_AddItemToObject(subObj,"othre",array);
// obj中添加key - value
cJSON_AddItemToObject(obj,"奔驰",subObj);
// 数据格式化
char* data = cJSON_Print(obj);
FILE* fp = fopen("car.json","w");
fwrite(data,sizeof(char),strlen(data)+1,fp);
fclose(fp);
return 0;
}
gcc *.c -o app -lm -I./include
{
"奔驰": {
"factory": "一汽大众",
"last": 31,
"price": 83,
"sell": 49,
"sum": 80,
"othre": [123, 1, "hello,world", {
"梅塞奔驰": "心所向,持以恒"
}]
}
}
cJSON解析json文件