二维码
微世推网

扫一扫关注

当前位置: 首页 » 快闻头条 » 科技 » 正文

cJSON使用教程_json文件存取_cJSON实体

放大字体  缩小字体 发布日期:2022-02-20 23:31:28    作者:熊覃艺    浏览次数:935
导读

cJson使用有如下json数据,我们学习如何解析它:{ "id":100, "username":"maye", "password":"123456", "online":false}从文件读取json数据首先我们从文件中获取js

cJson使用

有如下json数据,我们学习如何解析它:

{ "id":100, "username":"maye", "password":"123456", "online":false}


从文件读取json数据

首先我们从文件中获取json数据:

const char* jsonFromFile(const char* filename){FILE* fp = fopen(filename, "r");if (!fp){return NULL;}fseek(fp, 0, SEEK_END);long len = ftell(fp);fseek(fp, 0, SEEK_SET);char* buf = calloc(len+1, sizeof(char));fread(buf, sizeof(char), len, fp);fclose(fp);return buf;}int main(){ const char* jsondata = jsonFromFile("test.json");printf("%s\n", jsondata);cJSON*root=cJSON_Parse(jsondata);//解析json数据 //TODO 在这插入其他代码 free(jsondata);//释放内存 cJSON_free(root); return 0;}

获取cJSON文本

在解析或者生成json数据之后,如果需要从cJSON实体中获得文本,可以使用以下四种方式。

cJSON_Print

函数原型:char * cJSON_Print(const cJSON *item);

该函数将一个cJSON实体渲染为字符串(有格式),注意:返回得字符串需要手动释放内存

char* cjson = cJSON_Print(root);printf("%s\n", cjson);cJSON_free(cjson);//释放

效果:

cJSON_PrintUnformatted

函数原型:char * cJSON_PrintUnformatted(const cJSON *item);

该函数将一个cJSON实体渲染为字符串(无格式,所占内存更小,便于传输),注意:返回得字符串需要手动释放内存

cjson = cJSON_PrintUnformatted(root);printf("%s\n", cjson);cJSON_free(cjson); //释放

效果:

cJSON_PrintBuffered

函数原型:char * cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt)

使用缓冲策略将一个cJSON实体呈现为文本。Prebuffer是对蕞终大小得猜测。“猜得好”减少了再分配,提升了效率。Fmt 指定是否格式化json数据。注意:返回得字符串需要手动释放内存

cjson = cJSON_PrintBuffered(root, strlen(jsondata) + 5, cJSON_True);printf("%s\n", cjson);cJSON_free(cjson); //释放

cJSON_PrintPreallocated

使用已经在内存中分配得具有给定长度得缓冲区将一个cJSON实体渲染为文本。成功时返回1,失败时返回0。 注意:返回值为是否渲染成功,使用缓冲区之前先进行判断

char buf[1024] = { 0 };//预先准备缓冲区cJSON_bool ret = cJSON_PrintPreallocated(root, buf, sizeof(buf), cJSON_True);if (ret){printf("%s\n", buf);}//这里就不需要释放了

json数据写入文件

获得json文本之后,我们就可把它保存起来了,同样使用文件操纵,非常滴简单!

//把json数据写入文件,返回写入成功得字节数int jsonSaveFile(const char* filename,const char* cjson){FILE* fp = fopen(filename, "w");if (!fp){return NULL;}size_t len = fwrite(cjson, sizeof(char), strlen(cjson), fp);fclose(fp);return len;}int main(){const char* jsondata = jsonFromFile("test.json");cJSON* root = cJSON_Parse(jsondata);//解析json数据free(jsondata);//释放内存//将一个cJSON实体渲染为字符串(无格式,所占内存更小,便于传输),注意:同上cjson = cJSON_PrintUnformatted(root);printf("%s\n", cjson);jsonSaveFile("format.json", cjson);cJSON_free(cjson);cJSON_free(root);return 0;}

结果:

cJSON解析json数据和从文件读取,保存到文件得内容就到这啦~接下来会为大家带来更多cJSON库使用技巧,喜欢得不如点个“在看”吧

 
(文/熊覃艺)
免责声明
• 
本文仅代表发布者:熊覃艺个人观点,本站未对其内容进行核实,请读者仅做参考,如若文中涉及有违公德、触犯法律的内容,一经发现,立即删除,需自行承担相应责任。涉及到版权或其他问题,请及时联系我们删除处理邮件:weilaitui@qq.com。
 

Copyright©2015-2025 粤公网安备 44030702000869号

粤ICP备16078936号

微信

关注
微信

微信二维码

WAP二维码

客服

联系
客服

联系客服:

24在线QQ: 770665880

客服电话: 020-82301567

E_mail邮箱: weilaitui@qq.com

微信公众号: weishitui

韩瑞 小英 张泽

工作时间:

周一至周五: 08:00 - 24:00

反馈

用户
反馈