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;
}