0%

cJSON的使用

1. JSON格式

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。同时也易于机器解析和生成。

JSON建构于两种结构:
键值对的集合(A collection of name/value pairs)
值的有序列表(An ordered list of values)

2. cJSON

c语言中处理json格式的数据,可以借助于cJSON函数库,简单且效率高。

cJSON的开源仓库地址: https://github.com/DaveGamble/cJSON

cJSON.h定义了结构体cJSON来描述JSON对象,定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
typedef struct cJSON
{
/* 对象或数组链表的前后节点 */
struct cJSON *next;
struct cJSON *prev;
/* 对象火数组链表的子节点 */
struct cJSON *child;

/* 键值的类型 */
int type;

/* 保存键值字符串 */
char *valuestring;

int valueint;
double valuedouble;

/* 保存键值的名字 */
char *string;
} cJSON;

2.1 cJSON API

2.1.1 cJSON_Parse

1
2
3
4
5
/*
* @func: 解析JSON格式数据,按照cJSON结构进行序列化
* @ret: 成功返回指向内存块中cJSON的指针,失败返回NULL
*/
(cJSON *) cJSON_Parse(const char *value)

2.1.2 cJSON_Print

1
2
3
4
5
/*
* @func: 解析cJSON格式数据,转换成JSON格式的字符串
* @ret: 成功返回指向内存块中JSON字符串的地址,失败返回NULL
*/
(char *) cJSON_Print(const cJSON *item)

2.1.3 cJSON_Delete

1
2
3
4
5
/* 
* @func: 删除释放cJSON及其子节点。
* @ret:
*/
(void) cJSON_Delete(cJSON *item)

2.1.4 cJSON_CreateObject

1
2
3
4
5
/*
* @func: 创建新的cJSON对象
* @ret: 成功返回指向内存块中cJSON的指针,失败返回NULL
*/
(cJSON *) cJSON_CreateObject(void)

2.1.5 cJSON_GetObjectItem

1
2
3
4
5
/*
* @func: 获取JSON字符串字段值
* @ret: 成功返回指向内存块中cJSON的指针,失败返回NULL
*/
(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)

2.2 如何解析JSON格式

以github仓库README.md中JSON数据为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"name": "Awesome 4K",
"resolutions": [
{
"width": 1280,
"height": 720
},
{
"width": 1920,
"height": 1080
},
{
"width": 3840,
"height": 2160
}
]
}

2.2.1 转换JSON格式为cJSON

1
2
3
4
5
cJSON *monitor_json = cJSON_Parse(monitor);
if (monitor_json == NULL)
{

}

2.2.2 解析字符串数据

1
2
3
4
5
name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name");
if (cJSON_IsString(name) && (name->valuestring != NULL))
{

}

2.2.3 解析数组数据

1
2
3
4
5
6
resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");
cJSON_ArrayForEach(resolution, resolutions)
{
cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width");
cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height");
}

2.2.4 释放内存

1
cJSON_Delete(monitor_json);

2.3 如何生成JSON格式

2.3.1 创建cJSON结构体

1
cJSON *monitor = cJSON_CreateObject();

2.3.2 添加字符串数据

1
cJSON_AddStringToObject(monitor, "name", "Awesome 4K");

2.3.3 添加数组数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
resolutions = cJSON_AddArrayToObject(monitor, "resolutions");

for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index)
{
cJSON *resolution = cJSON_CreateObject();

if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL)
{
goto end;
}

if(cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL)
{
goto end;
}

cJSON_AddItemToArray(resolutions, resolution);
}

2.3.4 格式化JSON数据

1
char *string = cJSON_Print(monitor);

2.3.5 释放内存

1
2
cJSON_free(string);
cJSON_Delete(monitor);