C++开发工具库之 JSON for Modern C++

tech2022-11-27  98

起初从c#项目组转到c++开发,非常难以忍受的是json序列化和反序列化。c#下使用newman json工具做序列化只需要在需要序列化的class上添加[Serializable],直接调用静态方法SerializeObject即可;相比之下c++的序列化可以用极其boring形容。不过简单对比之后发现项目中使用的JSON for Modern C++还真是老大优中选优出来的,JSON for Modern c++在一众c++ json库中算是好用的了。

1.部署简单,单文件hpp,加入项目,include到文件即可。

2.语法清楚,json对象使用起来就如普通对象一般。

3.和stl完美结合,vector,list无需另外处理。

也有缺点,

据说内存上设计存在些许冗余,例如int值统一默认为int64;另外执行速度没有另外几个,如cJSON 高。但是目前的项目,不刻意追求执行速度。

示例如下:

#include <string> #include "json.hpp" using namespace std; using nlohmann::json; namespace ns { struct LoginInfo { int m_id; }; void to_json(json& j, const LoginInfo &data); void from_json(const json& j, LoginInfo &data); } void ns::to_json(json & j, const LoginInfo & data) { j[g_jId] = data.m_id; } void ns::from_json(const json & j, LoginInfo & data) { if (j.end() != j.find(g_jId)) { data.m_id = j[g_jId].get<int>(); } } namespace ns { template<class T> void to_string(const T &data, std::string &content) { json j; to_json(j, data); content = j.dump(); } template<class T> void from_string(const std::string &content, T &data) { try { json j = json::parse(content); from_json(j, data); } catch (exception* e) { } } }

 

最新回复(0)