0. 准备工作 github 官方地址是 https://github.com/DaveGamble/cJSON 安装 环境是 Ubuntu 20.04。需要先安装cmake。 apt install cmake 1、具体操作如下 在linux上找个地方 git clone https://github.com/DaveGamble/cJSON.git cd cJSON/ mkdir build cd build/ cmake .. make make install 执行完上述命令后, cJSON.h 头文件会安装在 /usr/local/include/cjson 目录下。 libcjson.so 库文件会安装在 /usr/local/lib 目录下。 2、配置下变量 还需要将/usr/local/lib目录添加到 /etc/ld.so.conf 文件中, vi /etc/ld.so.conf 然后添加 include /usr/local/lib 保存后,执行 /sbin/ldconfig 否则程序在运行时会报 error while loading shared libraries: libcjson.so.1: cannot open shared object file: No such file or directory 错误。 3. 程序编译测试 #include
#include #include "cjson/cJSON.h" int main(void) { char *json_data = NULL; char *data = "{"love":["LOL","Go shopping"]}"; //从缓冲区中解析出JSON结构 cJSON * json= cJSON_Parse(data); //将传入的JSON结构转化为字符串 并打印 json_data = cJSON_Print(json); printf("data:%sn", json_data); json = cJSON_CreateObject(); cJSON_AddStringToObject(json, "name", "lilei"); cJSON_AddStringToObject(json, "sex", "man"); cJSON_AddNumberToObject(json, "age", 18); cJSON_AddItemToObject(json,"love",array=cJSON_CreateArray()); cJSON_AddItemToArray(array,cJSON_CreateString("LOL")); cJSON_AddItemToArray(array,cJSON_CreateString("NBA")); cJSON_AddItemToArray(array,cJSON_CreateString("Girls")); cJSON_AddNumberToObject(json,"score",61); cJSON_AddStringToObject(json,"address","shanghai"); cJSON_AddItemToObject(json,"name",cJSON_CreateString("韩梅梅")); cJSON_AddStringToObject(json, "sex", cJSON_CreateString("girl")); // cJSON_AddNumberToObject(json,"age",cJSON_CreateNumber(17)); cJSON_AddNumberToObject(json,"age",17); cJSON_AddItemToObject(json,"love",array=cJSON_CreateArray()); cJSON_AddItemToArray(array,cJSON_CreateString("BOOK")); cJSON_AddItemToArray(array,cJSON_CreateString("Music")); cJSON_AddItemToArray(array,cJSON_CreateString("Go shopping")); cJSON_AddNumberToObject(json,"score",99); cJSON_AddStringToObject(json,"address","beijing"); cJSON_AddStringToObject(json, "name", "小红"); cJSON_AddStringToObject(json, "sex", "female"); cJSON_AddNumberToObject(json, "age", 18); cJSON_AddItemToObject(json,"love",array = cJSON_CreateObject()); cJSON_AddItemToObject(array, "爱好1", cJSON_CreateString("LOL")); cJSON_AddItemToObject(array, "爱好2", cJSON_CreateString("NBA")); cJSON_AddStringToObject(array, "爱好3", cJSON_CreateString("Girls")); cJSON_AddNumberToObject(json,"score",81); cJSON_AddStringToObject(json,"address","hk"); json_data = cJSON_Print(json); printf("n***************************n%sn", json_data); //将JSON结构所占用的数据空间释放 free(json_data); cJSON_Delete(json); return 0; }
编译 : gcc -o testjson -g testJson.c -lcjson -lm 执行 : ./testjson