简易好用的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

}

}

}

}

相关推荐
saltymilk6 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥7 小时前
C++ lambda 匿名函数
c++
算家计算11 小时前
7B参数拿下30个世界第一!Hunyuan-MT-7B本地部署教程:腾讯混元开源业界首个翻译集成模型
人工智能·开源
FIT2CLOUD飞致云12 小时前
SQLBot开源智能问数系统成功进入GitHub趋势榜主榜,Star数突破2,000个!
开源
沐怡旸13 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥13 小时前
C++ 内存管理
c++
scilwb19 小时前
Isaac Sim机械臂教程 - 阶段1:基础环境搭建与机械臂加载
人工智能·开源
杨杨杨大侠19 小时前
Atlas Mapper 案例 01:初级开发者 - 电商订单系统开发
java·开源·github
博笙困了19 小时前
AcWing学习——双指针算法
c++·算法
感哥20 小时前
C++ 指针和引用
c++