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

}

}

}

}

相关推荐
xiaolang_8616_wjl4 小时前
c++文字游戏_闯关打怪2.0(开源)
开发语言·c++·开源
夜月yeyue4 小时前
设计模式分析
linux·c++·stm32·单片机·嵌入式硬件
NocoBase5 小时前
NocoBase 商业授权激活指南
低代码·开源·资讯
无小道5 小时前
c++-引用(包括完美转发,移动构造,万能引用)
c语言·开发语言·汇编·c++
FirstFrost --sy7 小时前
数据结构之二叉树
c语言·数据结构·c++·算法·链表·深度优先·广度优先
Tanecious.7 小时前
C++--map和set的使用
开发语言·c++
Yingye Zhu(HPXXZYY)7 小时前
Codeforces 2021 C Those Who Are With Us
数据结构·c++·算法
liulilittle8 小时前
LinkedList 链表数据结构实现 (OPENPPP2)
开发语言·数据结构·c++·链表
无聊的小坏坏9 小时前
三种方法详解最长回文子串问题
c++·算法·回文串