[源码分析]-轻量级JSON-cJson

本文介绍了轻量级JSON库cJson,包括其简介、JSON基础知识,如语法、优缺点和应用场景,并详细分析了cJson的数据结构、函数库、实现和使用方法。
摘要由CSDN通过智能技术生成

[源码分析]-轻量级JSON-cJson

second60 20180612

1. cJSON简介

cJson是个轻量级的C语言JSON库,速度快,而且代码少,只有两个文件:cJSON.hcJSON.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) jsonxml体积小

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
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值