1:安装
环境是 Ubuntu 18.04。需要先安装cmake。
cJSON 库安装步骤如下:
git clone https://github.com/DaveGamble/cJSON.git
cd cJSON/
mkdir build
cd build/
cmake …
make make install
2:结构体
2.1: cJSON
typedef struct cJSON
{
struct cJSON *next;
struct cJSON *prev;
struct cJSON *child;
int type;
char *valuestring;
int valueint;
double valuedouble;
char *string;
} cJSON;
next 和prev :Cjson结构体作为一个双向连表的环,可以通过 next 和prev 指针进行连表遍历
child:可以是cJSON_Array、cJSON_Object类型数据
type:当前项的类型
valuestring:内容存储,当类型是cJSON_String和cJSON_Raw
valueint:内容存储,整型,可以是cJSON_False、cJSON_True数据
valuedouble:内容存储,浮点型,当类型是cJSON_Number
string:键名
3:cJSON解析
3.1: cJSON_Parse
JSON *cJSON_Parse(const char *value);
作用:将一个JSON数据包,按照cJSON结构体的结构序列化整个数据包,并在堆中开辟一块内存存储cJSON结构体
返回值:成功返回一个指向内存块中的cJSON的指针,失败返回NULL
3.2: cJSON_Print
char *cJSON_Print(cJSON *item);
作用:将cJSON数据解析成JSON字符串,并在堆中开辟一块char*的内存空间存储JSON字符串
返回值:成功返回一个char*指针该指针指向位于堆中JSON字符串,失败返回NULL
3.3 :cJSON_PrintUnformatted
与cJSON_Print功能类似。
4:创建
4.1:cJSON_CreateObject
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
创建一个JSON对象,之后便可向这个对象中添加string或int等内容的数据项了。使用该函数会通过malloc()函数在内存中开辟一个空间,使用完成需要手动释放。
其他创建
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* Create a string where valuestring references a string so
* it will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
/* Create an object/array that only references it's elements so
* they will not be freed by cJSON_Delete */
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
/* These utilities create an Array of count items.
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
5:添加
5.1:cJSON_AddItemToObject
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
作用:向一个object对象添加,一个命名string 的 object 对象item
5.2:cJSON_AddItemToArray
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
在数组中添加元素
cJSON *array :表示需要执行添加元素的数组
cJSON *item:要添加的数组对象
其他添加
/* Append item to the specified array/object. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
* writing to `item->string` */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
6:删除
6.1:cJSON_Delete() 和 cJSON_free
创建cjson对象后,处理完需要进行内存释放:
如果是cjson里的对象,请使用cJSON_Delete()
如果不是对象:cJSON_free()或free()
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
CJSON_PUBLIC(void) cJSON_free(void *object);
7:获取
7.1:cJSON_GetObjectItem
cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);
作用:获取JSON字符串字段值
返回值:成功返回一个指向cJSON类型的结构体指针,失败返回NULL
其他获取
7.2:cJSON_GetArraySize
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
获取数组中元素的格式,并返回
7.3:cJSON_GetArrayItem
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
获取数组中元素中第index个数据元素并返回
/* Returns the number of items in an array (or object). */
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
/* Get item "string" from object. Case insensitive. */
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
/* Check item type and return its value */
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item)
8:局部元素操作
8.1:局部元素删除和分离
8.1.1:cJSON_DeleteItemFromArray
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
作用删除数组中的数组元素
cJSON *array :表示需要执行删除的元素的数组
int which:要删除第几个元素
/* Remove/Detach items from Arrays/Objects. */
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
8.2:局部元素更新
8.1.1:cJSON_ReplaceItemInObject
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
将object中键值名为string的键值替换成cJSON类型的newitem
其他替换
/* Update array items. */
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
3:解析示例
/*************************************************************************
> File Name: cjosn-test.c
> Author: kayshi
> Mail: kayshi2019@qq.com
> Created Time: Fri 09 Oct 2020 10:53:47 AM CST
************************************************************************/
#include <stdio.h>
#include "cJSON.h"
int main()
{
cJSON *cjson, *test_1,*test_2, *test_3;
char *json_string = "{\"test_1\":\"0\",\"test_2\":\"1\",\"test_3\":2}";
cjson = cJSON_Parse(json_string);
if(cjson == NULL)
{
printf("json pack into cjson error...\n");
}
else
{
cJSON_Print(cjson);
}
#if 0 //method 1
char *test_1_string = cJSON_GetObjectItem(cjson, "test_1")->valuestring;
char *test_2_string = cJSON_GetObjectItem(cjson, "test_2")->valuestring;
char *test_3_string = cJSON_GetObjectItem(cjson, "test_3")->valueint;
printf("%s\n", test_1_string);
printf("%s\n", test_2_string);
printf("%d\n", test_3_string);
#else //method 2
test_1 = cJSON_GetObjectItem(cjson, "test_1");
test_2 = cJSON_GetObjectItem(cjson, "test_2");
test_3 = cJSON_GetObjectItem(cjson, "test_3");
printf("%s\n", test_1->valuestring);
printf("%s\n", test_2->valuestring);
printf("%d\n", test_3->valueint);
#endif
cJSON_Delete(cjson);
}
编译运行
kayshi@ubuntu:~/code/cJSON-test$ gcc cjosn-test.c -I/home/kayshi/install/cJSON/ -lcjson
kayshi@ubuntu:~/code/cJSON-test$ ./a.out
0
1
2
4:设置json数组结构
/*************************************************************************
> File Name: cjosn-create.c
> Author: kayshi
> Mail: kayshi2019@qq.com
> Created Time: Fri 09 Oct 2020 01:30:27 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
cJSON *root, *js_body;
root = cJSON_CreateArray();
cJSON_AddItemToArray(root, cJSON_CreateString("Hello world"));
cJSON_AddItemToArray(root, cJSON_CreateNumber(10));
char *s = cJSON_Print(root);
//char *s = cJSON_PrintUnformatted(root);
if(s)
{
printf("%s \n", s);
free(s);
}
if(root)
cJSON_Delete(root);
return 0;
}
执行
ayshi@ubuntu:~/code/cJSON-test$ gcc cjosn-create.c -I/home/kayshi/install/cJSON/ -lcjson
kayshi@ubuntu:~/code/cJSON-test$ ./a.out
["Hello world", 10]
5:设置j复杂的json结构
/*************************************************************************
> File Name: cjosn-create.c
> Author: kayshi
> Mail: kayshi2019@qq.com
> Created Time: Fri 09 Oct 2020 01:30:27 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
cJSON *root, *js_body, *js_list;
root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "body", js_body = cJSON_CreateArray());
cJSON_AddItemToArray(js_body, js_list = cJSON_CreateObject());
cJSON_AddStringToObject(js_list, "name", "kayshi");
cJSON_AddNumberToObject(js_list, "status", 100);
char *s = cJSON_Print(root);
//char *s = cJSON_PrintUnformatted(root);
if(s)
{
printf("%s \n", s);
free(s);
}
if(root)
cJSON_Delete(root);
return 0;
}
执行
kayshi@ubuntu:~/code/cJSON-test$ gcc cjosn-create.c -I/home/kayshi/install/cJSON/ -lcjson
kayshi@ubuntu:~/code/cJSON-test$ ./a.out
{
"body": [{
"name": "kayshi",
"status": 100
}]
}