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

起初从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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值