简易好用的C++结构体与JSON文本相互转换开源库

开源库地址: https ://github .com /bk192077 /struct_mapping .git

支持结构体,std::strng, std::vcetor, std::list, std::map, std::multimap等类型

注意:需要std c++17 及以上版本支持

测试程序:

cpp 复制代码
#include "struct_mapping/struct_mapping.h"

#include <list>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <vector>

struct Point
{
	Point()
	{
		struct_mapping::reg(&Point::x, "x");
		struct_mapping::reg(&Point::y, "y");	
		struct_mapping::reg(&Point::z, "z");

	}

	double x = 0.1;
	double y = 0.2;
	double z = 0.3;
};

struct LL
{
	LL()
	{
		struct_mapping::reg(&LL::str, "str");
		struct_mapping::reg(&LL::mlt, "mlt");
	}
	std::string str = "abc";
	std::map<std::string ,int> mlt = {{"zero", 0}, {"one", 1}, {"two", 2}};
};

struct President
{
	President()
	{
		struct_mapping::reg(&President::name, "name");
		struct_mapping::reg(&President::mass, "mass");
		struct_mapping::reg(&President::vec, "vec");
		struct_mapping::reg(&President::lst, "lst");
		struct_mapping::reg(&President::l, "l");
	}
	std::string name="xiaoli-feidao";
	double mass=123.4;
	std::vector<int> vec={1,2,3,4,5};
	std::list<std::string> lst={"abc","def"};
	LL l;
};

struct USA
{
	USA()
	{
		struct_mapping::reg(&USA::president, "president");
	}

	President president;
};

int main()
{
	USA u;
	std::ostringstream out;
	struct_mapping::map_struct_to_json(u, out, " ");//something out stream directly
	std::cout << std::endl;

#if 0
	std::cout << out.str() << std::endl;
#endif
	
	u.president.name = "JACK-LEE";
  u.president.mass = 76.5;
	u.president.lst.push_back("Zara");
	u.president.l.str="Scientific Persons";
	u.president.l.mlt["aaa"] = -2;
	u.president.l.mlt["bbb"] = -1;
	struct_mapping::map_struct_to_json(u, out, " ");
	std::cout << out.str() << std::endl;

#if 0		
	LL AB;
	AB.str = "Scientific Persons";
	AB.mlt["aaa"] = -2;
	AB.mlt["bbb"] = -1;
	struct_mapping::map_struct_to_json(AB, out, "	");
	std::cout << std::endl << out.str() << std::endl;
#endif
}

构建指令: g++ ./struct-lys.cpp -std=c++17 -o sl.out -I /home/lys/usr/local/include

运行结果

{

"president": {

"name": "xiaoli-feidao",

"mass": 123.4,

"vec": [

1,

2,

3,

4,

5

],

"lst": [

"abc",

"def"

],

"l": {

"str": "abc",

"mlt": {

"one": 1,

"two": 2,

"zero": 0

}

}

}

}{

"president": {

"name": "JACK-LEE",

"mass": 76.5,

"vec": [

1,

2,

3,

4,

5

],

"lst": [

"abc",

"def",

"Zara"

],

"l": {

"str": "Scientific Persons",

"mlt": {

"aaa": -2,

"bbb": -1,

"one": 1,

"two": 2,

"zero": 0

}

}

}

}

相关推荐
hikktn18 分钟前
开源宝藏:Smart-Admin 重复提交防护的 AOP 切面实现详解
开源
charley.layabox18 分钟前
LayaAir引擎荣获开源大赛一等奖
开源
键盘上的蚂蚁-19 分钟前
利用开源图床的技巧与实践
开源
Hugging Face21 分钟前
Halo 正式开源: 使用可穿戴设备进行开源健康追踪
开源
OpenCloudOS23 分钟前
开源生态发展合作倡议
开源
南东山人3 小时前
一文说清:C和C++混合编程
c语言·c++
n***85946 小时前
嵌入式 UI 开发的开源项目推荐
windows·开源·开源软件
Ysjt | 深6 小时前
C++多线程编程入门教程(优质版)
java·开发语言·jvm·c++
ephemerals__6 小时前
【c++丨STL】list模拟实现(附源码)
开发语言·c++·list