CJsonObject
CJsonObject 通过CSDN官方开发的【猿如意】客户端进行下载安装。
猿如意是一款面向开发者的辅助开发工具箱,包含了效率工具、开发工具下载,教程文档,代码片段搜索,全网搜索等功能模块。帮助开发者提升开发效率,帮你从“问题”找到“答案”。
点击链接,登录猿如意官网即可下载https://devbit.csdn.net?source=csdn_community
【猿如意】安装完成后,在顶部搜搜框输入链接c++ CJsonObject 读写json_子建莫敌的博客-CSDN博客_cjsonobject,选择下方“全网搜索”然后点击打开文章,获取文章里面的链接“ GitHub地址:https://github.com/Bwar/CJsonObject”即可下载对应的开发工具,之后按步骤即可完成安装。

CJsonObject是Bwar基于cJSON全新开发一个C++版的JSON库,CJsonObject的最大优势是简单、轻量、跨平台,开发效率极高,尤其对多层嵌套json的读取和生成、修改极为方便。CJsonObject比cJSON简单易用得多,且只要不是有意不释放内存就不会发生内存泄漏。用CJsonObject的好处在于完全不用专门的文档,头文件即文档,所有函数都十分通俗易懂,最为关键的一点是解析JSON和生成JSON的编码效率非常高。
GitHub地址:https://github.com/Bwar/CJsonObject
简单到只需往项目添加四个文件:cJson.h、cJson.c、CJsonObject.hpp、CJsonObject.cpp。

在使用时只需包含一个头文件
#include "CJsonObject.hpp"
vs2019编译提示“ error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.”
解决办法:在vs项目属性 ——C/C++——预处理——预处理器定义中新增,添加“_CRT_SECURE_NO_WARNINGS”,如下图所示:
- #include
- void writeJsonFile(const std::string fileName)
- {
- std::ofstream os(fileName);
- if (!os) return;
-
- neb::CJsonObject root;
- root.Add("age", 21);
-
- neb::CJsonObject friendsObj;
- friendsObj.Add("firend_age", 21);
- friendsObj.Add("firend_name", "ZhouWuxian");
- friendsObj.Add("firend_sex", "man");
- root.Add("friends", friendsObj);
-
- neb::CJsonObject hobbyObj;
- hobbyObj.Add("sing");
- hobbyObj.Add("run");
- hobbyObj.Add("Tai Chi");
-
- root.Add("hobby", hobbyObj);
- root.Add("name", "shuiyixin");
- root.Add("sex", "man");
-
- //os << root.ToString(); // 格式化输出
- os << root.ToFormattedString(); // 非格式化输出
-
- os.close();
-
- return;
- }

- #include
- void readJsonFile(const std::string fileName)
- {
- std::ifstream file;
- file.open(fileName, std::ios::in);
-
- //指针定位到文件末尾
- file.seekg(0, std::ios::end);
- int fileLength = file.tellg();
-
- //指定定位到文件开始
- file.seekg(0, std::ios::beg);
-
- char* buffer = new char[fileLength + 1];
- file.read(buffer, fileLength);
- buffer[fileLength] = '\0';
-
- std::string strJson = buffer;
-
- if (buffer) {
- delete[] buffer;
- }
- file.close();
-
- neb::CJsonObject root;
- if (!root.Parse(strJson)) return;
-
- int age = 0;
- root.Get("age", age);
-
- root.Add("age", 21);
-
- neb::CJsonObject friendsObj;
- root.Get("friends", friendsObj);
- if (friendsObj.IsEmpty()) return;
-
- int friend_age = 0;
- friendsObj.Get("firend_age", friend_age);
-
- std::string friend_name;
- friendsObj.Get("firend_name", friend_name);
-
- std::string friend_sex;
- friendsObj.Get("firend_sex", friend_sex);
-
- neb::CJsonObject hobbyObj;
- root.Get("hobby", hobbyObj);
- if (hobbyObj.IsEmpty() && hobbyObj.IsArray()) return;
-
- for (int i = 0; i < hobbyObj.GetArraySize(); ++i) {
- std::string info;
- hobbyObj.Get(i, info);
- std::cout << info << std::endl;
- }
-
- std::string name;
- root.Get("name", name);
-
- std::string sex;
- root.Get("sex", sex);
-
- return;
- }