用C语言玩JSON


JSON是网络上常见的数据传输格式之一,尤其AJAX常用。最近想用C++解析JSON,查了一下JSON的官方网站,翻出来一个不错的库——cJSON库。貌似使用的人不是很多,但是只有两个文件,代码量不大,基本实现了常见的所有功能,用起来还是挺方便的。

--------------------------------------分割线 --------------------------------------

Struts中异步传送XML和JSON类型的数据

Linux下JSON库的编译及代码测试

jQuery 获取JSON数据[$.getJSON方法]

用jQuery以及JSON包将表单数据转为JSON字符串

在C语言中解析JSON配置文件

--------------------------------------分割线 --------------------------------------

cJSON的网址:http://sourceforge.net/projects/cjson/

打开cJSON.h文件看看数据类型和函数名基本上就能上手了。

主要数据类型:

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. */
 
	char *valuestring;			/* The item's string, if type==cJSON_String */
	int valueint;				/* The item's number, if type==cJSON_Number */
	double valuedouble;			/* The item's number, if type==cJSON_Number */
 
	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结构体,使用了链表存储方式。type代表这个结构体的类型,包括数、字符串、数组、json对象等。如果代表的是实数,则valuedouble就存储了这个实数取值,其余成员类似容易看懂。

几个常用函数

extern cJSON *cJSON_Parse(const char *value);//解析一个json字符串为cJSON对象
extern char  *cJSON_Print(cJSON *item);//将json对象转换成容易让人看清结构的字符串
extern char  *cJSON_PrintUnformatted(cJSON *item);//将json对象转换成一个很短的字符串,无回车
extern void   cJSON_Delete(cJSON *c);//删除json对象
extern int	  cJSON_GetArraySize(cJSON *array);//返回json数组大小
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//返回json数组中指定位置对象
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//返回指定字符串对应的json对象
extern cJSON *cJSON_CreateIntArray(int *numbers,int count);//生成整型数组json对象
extern void cJSON_AddItemToArray(cJSON *array, cJSON *item);//向数组中添加元素

README文件中也提供了一些简单的说明和例子程序。cJSON是个简单而好用的C语言JSON库,需要用C/C++处理JSON的话强烈推荐~

本文永久更新链接地址:

相关内容