c 语言json-c实例,cJSON编程示例

1.程序源码

#include

#include

#include

#include

#include

/*计算文件大小*/

int file_size(char *filename)

{

FILE *fp = fopen(filename,"r");

int size = 0;

if(!fp)

return -1;

fseek(fp,0L,SEEK_END);

size = ftell(fp);

fclose(fp);

return size;

}

int read_all(char *src_file, char *buf, int size)

{

FILE *fp = fopen(src_file,"r");

int i = 0;

if(fp < 0)

return -1;

for(i=0; !feof(fp) && i

{

buf[i] = fgetc(fp);

}

buf[i] = 0x00;

fclose(fp);

return i;

}

int main()

{

FILE *fp = NULL;

cJSON *json = NULL;

char *filename = "./exapmle.json";

char *out;

char *buf = NULL;

int len = file_size(filename);

if(len <= 0)

return -1;

buf = malloc(len+1);

if(buf == NULL)

{

printf("内存不足\n");

return -1;

}

len = read_all("./1.json", buf, len);

json = cJSON_Parse(buf);

if(!json)

{

printf("Error before: [%s]\n",cJSON_GetErrorPtr());

return -1;

}

out = cJSON_Print(json); //这个是可以输出的。为获取的整个json的值

cJSON *arrayItem = cJSON_GetObjectItem(json,"syslog_db"); //获取这个对象成员

cJSON *object = cJSON_GetArrayItem(arrayItem,0); //因为这个对象是个数组获取,且只有一个元素所以写下标为0获取

/*下面就是可以重复使用cJSON_GetObjectItem来获取每个成员的值了*/

cJSON *item = cJSON_GetObjectItem(object,"db_user"); //

printf("db_user:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"db_password");

printf("db_password:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"db_type");

printf("db_type:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"db_ip");

printf("db_ip:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"db_port");

printf("db_port:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"db_name");

printf("db_name:%s\n",item->valuestring);

item = cJSON_GetObjectItem(object,"sql");

printf("db_sql:%s\n",item->valuestring);

/*这里这个是直接可以获取值的*/

arrayItem = cJSON_GetObjectItem(json,"syslog_enable");

printf("%s\n",arrayItem->valuestring);

cJSON_Delete(json);

free(buf);

return 0;

}

2.json文件

{

"syslog_db":

[{"db_user": "xxx",

"db_password": "yyy",

"db_type": "ORACLE",

"db_ip":"172.16.1.248",

"db_port":"1521",

"db_name":"orcl",

"sql":"select * from syslog"

}],

"syslog_source":

[{"send_ip":"172.0.0.8",

"send_port":"8",

"send_protocal":"TCP"

}],

"syslog_enable":"1"

}

4.编译源码

$ gcc -o example example.c -L$HOME/local/lib -lcjson

5.运行程序

$ ./example

db_user:xxx

db_password:yyy

db_type:ORACLE

db_ip:172.16.1.248

db_port:1521

db_name:orcl

db_sql:select * from syslog

1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值