开源库地址: https://github.com/bk192077/struct_mapping.git
支持结构体,std::strng, std::vcetor, std::list, std::map, std::multimap等类型
注意:需要std c++17 及以上版本支持
测试程序:
- #include "struct_mapping/struct_mapping.h"
-
- #include
- #include
- #include
- #include
- #include
- #include
-
- 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
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
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
}
}
}
}