linux 编写c语言程序需要cjson库,用C语言玩JSON

JSON是网络上常见的数据传输格式之一,尤其AJAX常用。最近想用C++解析JSON,查了一下JSON的官方网站,翻出来一个不错的库——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的话强烈推荐~

0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值