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;
}
相关推荐
hmbbcsm几秒前
练习python题目小记(五)
开发语言·python
kokunka5 分钟前
C#类修饰符功能与范围详解
java·开发语言·c#
ShineWinsu11 分钟前
对于数据结构:链式二叉树的超详细保姆级解析—中
数据结构·c++·算法·面试·二叉树·校招·递归
仟濹16 分钟前
【Java 基础】3 面向对象 - this
java·开发语言·python
Dxy123931021622 分钟前
Python一个类的特殊方法有哪些
开发语言·python
爱吃烤鸡翅的酸菜鱼30 分钟前
如何用【rust】做一个命令行版的电子辞典
开发语言·rust
不爱学英文的码字机器41 分钟前
Rust 并发实战:使用 Tokio 构建高性能异步 TCP 聊天室
开发语言·tcp/ip·rust
liu****42 分钟前
20.传输层协议TCP
服务器·网络·数据结构·c++·网络协议·tcp/ip·udp
沐怡旸1 小时前
【穿越Effective C++】条款20:宁以pass-by-reference-to-const替换pass-by-value——参数传递的效率与语义
c++·面试
八个程序员1 小时前
c++音乐——《两只老虎》
c++·游戏