手机版
你好,游客 登录 注册
背景:
阅读新闻

用C语言玩JSON

[日期:2014-05-16] 来源:Linux社区  作者:Linux [字体: ]

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

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

Struts中异步传送XML和JSON类型的数据 http://www.linuxidc.com/Linux/2013-08/88247.htm

Linux下JSON库的编译及代码测试 http://www.linuxidc.com/Linux/2013-03/81607.htm

jQuery 获取JSON数据[$.getJSON方法] http://www.linuxidc.com/Linux/2013-03/81673.htm

用jQuery以及JSON包将表单数据转为JSON字符串 http://www.linuxidc.com/Linux/2013-01/77560.htm

在C语言中解析JSON配置文件 http://www.linuxidc.com/Linux/2014-05/101822.htm

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

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的话强烈推荐~

本文永久更新链接地址http://www.linuxidc.com/Linux/2014-05/101823.htm

linux
相关资讯       json  JSON C语言 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款