nlohmann::json 超简单序列化反序列化
上实例
cpp
#include <vector>
#include <string>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
namespace niumabufen
{
// 公共请求类
class JsonLocalMessage
{
public:
int m_nUserID{ 0 }; // 用户id
int m_nVesion{ 0 }; // 版本
std::string m_strCmd{ "" }; // 信令类型
// 类名,成员1,成员2
NLOHMANN_DEFINE_TYPE_INTRUSIVE(JsonLocalMessage, m_nUserID, m_nVesion, m_strCmd);
};
}
void test()
{
// 序列化
niumabufen::JsonLocalMessage stJsonLocalMessage ;
stJsonLocalMessage .m_nUserID = 0;
stJsonLocalMessage .m_nVesion= 1;
stJsonLocalMessage .m_strCmd = "Cmd";
json json_JsonLocalMessage = stJsonLocalMessage;
std::string strRes = json_JsonLocalMessage.dump();
std::cout << "Res:" << strRes << std::endl;
// 反序列化
auto config_json = nlohmann::json::parse(strRes );
JsonLocalMessage stLocalMessage = config_json;
std::cout << "UserID:" << stLocalMessage.m_nUserID << std::endl;
std::cout << "Vesion:" << stLocalMessage.m_nVesion<< std::endl;
std::cout << "Cmd:" << stLocalMessage.m_strCmd<< std::endl;
}
int main()
{
test();
return 0;
}