前言
上文介绍了结构体(类)与JSON相互转换需要的四个宏的区别——http://t.csdnimg.cn/shii6
本次将介绍结构体(类)与JSON相互转换时 可选择那些成员被转换,那些不转换
主要内容
使用nlohmann/json的宏去实现结构体转json的时候,我们可以选择需要转换的成员。
#include "iostream"
#include "myStruct.h"
#include "json.hpp"
using namespace std;
struct People
{
std::string name = "asd";
int age = 123;
std::string sex = "man";
int height = 190;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(People, name, age)
};
int main(void)
{
People people;
nlohmann::json json = people;
cout << "dump() <<" << json.dump() << endl;
return 0;
}
这里我仅在宏内包含了name 和 age。在将结构体转JSON后,将其打印。
dump() <<{"age":123,"name":"asd"}
可以看到仅转换了name 和 age。
同理,在将json字符串转结构体时,也仅会转换宏包含的成员。
#include "iostream"
#include "myStruct.h"
#include "json.hpp"
using namespace std;
struct People
{
std::string name;
int age;
std::string sex;
int height;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(People, name, age)
};
int main(void)
{
string jsonStr = "{\"age\":24, \"name\":\"asd\", \"weight\":120, \"height \":120}";
nlohmann::json js = nlohmann::json::parse(jsonStr);
People me = js.get<People>();
cout << "name::" << me.name << endl;
cout << "age::" << me.age << endl;
cout << "sex::" << me.sex << endl;
cout << "height::" << me.height << endl;
return 0;
}
需要注意,这里我将结构体内成员的初始化默认值给删除了,因为不删除的话,在结构体会给sex和height赋默认值,从而影响最终结果;
执行结果:
name::asd
age::24
sex::
height::0
// 不删除默认初始值的打印结果
// name::asd
// age::24
// sex::man
// height::190
结论
宏内包含的成员才会进行序列化与反序列华,所以我们仅需要把 需要转换的结构体(类)成员变量名写入宏中,就可以进行转换,且仅会转换宏中的成员变量。
扩展
宏仅支持63个成员变量。
宏总共支持64个参数,除了必须包含的结构体(类)名称外,剩下63个成员变量名。