nlohmann::json 超简单序列化反序列化

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;
}
相关推荐
ZouZou老师2 小时前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
ZouZou老师2 小时前
C++设计模式之桥接模式:以家具生产为例
c++·设计模式·桥接模式
diegoXie2 小时前
Python / R 向量顺序分割与跨步分割
开发语言·python·r语言
程序员小白条2 小时前
0经验如何找实习?
java·开发语言·数据结构·数据库·链表
呱呱巨基2 小时前
Linux 进程概念
linux·c++·笔记·学习
liulilittle3 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
ZouZou老师3 小时前
C++设计模式之组合模式:以家具生产为例
c++·设计模式·组合模式
yong15858553433 小时前
2. Linux C++ muduo 库学习——原子变量操作头文件
linux·c++·学习
失散133 小时前
Python——1 概述
开发语言·python
萧鼎3 小时前
Python 图像哈希库 imagehash——从原理到实践
开发语言·python·哈希算法