1.cJSON库
cJSON是C语言中的一个JSON编解码器,用于进行json操作中的序列化与反序列化。具有超轻便,可移植,单文件的特点,使用MIT开源协议。其中主要包括两个文件cjson.c和cjson.h。通过采用树形结构,将json中的键值看为一个个节点。
以以下字符串为例:
{
"ver": "1.0",
"cloud": {
"password": "12345678",
"mpassword": "12345678"
},
"data": [{
"key": 1,
"type": 2,
"val": "10"
},
{
"key": 2,
"type": 1,
"val": "0"
},
{
"key": 3,
"type": 3,
"val": "22.5"
}
]
}
将其看为树形结构可得
图中除去数组外,一个对象便是一个节点,图中的数组则是额外包含了三个对象,对象中便是键值对。
以下是cJSON库的部分定义
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);//从 给定的json字符串中得到cjson对象
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);//从cjson对象中获取有格式的json对象
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);//从cjson对象中获取无格式的json对象
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);//删除cjson对象,释放链表占用的内存空间
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);//获取cjson对象数组成员的个数
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//根据下标获取cjosn对象数组中的对象
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//根据键获取对应的值(cjson对象)