[源码分析]-轻量级JSON-cJson
second60 20180612
1. cJSON简介
cJson是个轻量级的C语言JSON库,速度快,而且代码少,只有两个文件:cJSON.h和cJSON.c。代码只有七百多行。
使用只需引入cJSON文件,一起编译即可,使用了数学库,要添加-lm库
g++ test.c cJSON.c -o test
gcc test.c cJSON.c -o test -lm
2. JSON知识
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
2.1 json 语法
在 JS 语言中,一切都是对象。因此,任何支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。但是对象和数组是比较特殊且常用的两种类型:
对象表示为键值对
数据由逗号分隔
花括号保存对象
方括号保存数组
对象:JSON最常用的格式是对象的键值对
{"firstName": "Json"}
数组:数组的方式也是使用方括号 []
{
"people":[
{
"firstName": "Brett",
"lastName":"McLaughlin"
},
{
"firstName":"Jason",
"lastName":"Hunter"
}
]
}
2.2 json的好处
a) 通用性,任何语言只要按照json格式,都可以互通使用
b) json的转换速度非常快
c) json比xml体积小
d) json的扩展性非常好,新加item只需多加key/value
2.3 json的劣点
a) json体积会比正常的流体积大很多,包括:引号,冒名,键名等,所以比网络中比较浪费流量
b) json递归深度有限制,如果深度很深,那么速度将会变慢,同时占用内存比较大
c) json字符串没有顺序,所以较难读懂
2.4 使用场所景
在大部份的项目中,都会使用json,因为json有语言无关性,只要都是json格式,都可以读取使用。
a) json配置。因为json解析速度比xml要快,要小,所以把配置转成json字符串,程序中读取将会非常快,配置可以放本地,也可以放redis中。
b) 网络格式。虽然json会比较大,但对于网络接口,可以用json格式,目的是json有很好的扩展性,加一个参数或返回值,是非常容易,而且不影响原有逻辑。
c) 跨语言交互。如两个不同语言交互,可以用json来进行交互。
总结,json是一个用途非常广泛,也非常好用的标准。
3. cJSON源码分析
3.1 cJSON数据结构
cJSON中包含两个结构,cJSON结构和cJSON_Hooks结构
// cJson 结构体
typedef struct cJSON {
// 双链表指针
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
// 孩子指什
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
// 类型
int type; /* The type of the item, as above. */
// 当类型为cJSON_String,此值有用
char *valuestring; /* The item's string, if type==cJSON_String */
// 当类型为cJSON_Number,下面值有用
int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */
// item名字
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
// cJson 函数指针钩子,用来实现不同的函数
typedef struct cJSON_Hooks {
void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks;
3.2 cJSON函数库
/* Supply malloc, realloc and free functions to cJSON */
extern void cJSON_InitHooks(cJSON_Hooks* hooks);
/* 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);
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char *cJSON_Print(cJSON *item);
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char *cJSON_PrintUnformatted(cJSON *item);
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt);
/* Delete a cJSON entity and all subentities. */
extern void cJSON_Delete(cJSON *c);
/* Returns the number of items in an array (or object). */
extern int cJSON_GetArraySize(cJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(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. */
extern const char *cJSON_GetErrorPtr(void);
/* These calls create a cJSON item of the appropriate type. */
extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);
/* These utilities create an Array of count items. */
extern cJSON *cJSON_CreateIntArray(const int *numbers,int count);
extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count);
extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count);
extern cJSON *cJSON_CreateStringArray(const char **strings,int count);
/* Append item to the specified array/object. */
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);
extern void cJSON_AddItemToObjectCS(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 */
/* Append r