Nlohmann::JSON支持json转结构体和结构体转json
只需要使用它的宏
nlohmann::json提供了四个宏来支持结构体与JSON相互转换
// 侵入式
NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT
NLOHMANN_DEFINE_TYPE_INTRUSIVE
// 非侵入式
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE
NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT
结构体转JSON
使用方式:
#include "iostream"
#include "myStruct.h"
#include "json.hpp"
using namespace std;
struct People
{
std::string name;
int age;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(People, name, age)
};
int main(void)
{
People me;
me.age = 24;
me.name = "asd";
nlohmann::json js = me;
cout << js.dump() << endl;
return 0;
}
输出结果:
{"age":24,"name":"asd"}
这里使用的是NLOHMANN_DEFINE_TYPE_INTRUSIVE宏。
具体使用方式就是在结构体内部使用该宏,将结构体名称和结构体成员放入;然后声明一个nlohmann::json 对象,将结构体赋值给该对象,就可以将结构体转换为JSON。
如果需要输出json字符串,则使用nlohmann::json成员函数 dump();
JSON字符串转结构体
将JSON字符串转结构体不需要多余的代码,依旧是使用宏。
代码示范如下:
#include "iostream"
#include "myStruct.h"
#include "json.hpp"
using namespace std;
struct People
{
std::string name;
int age;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(People, name, age)
};
int main(void)
{
string jsonStr = "{\"age\":24,\"name\":\"asd\"}";
nlohmann::json js = nlohmann::json::parse(jsonStr);
People me = js.get<People>();
cout << "name::" << me.name << endl;
cout << "age::" << me.age << endl;
return 0;
}
执行结果:
name::asd
age::24
可以看到,结构体没有变动;
更改的步骤是
- 使用nlohmann::json::parse() 去解析json字符串,从而获得nlohmann::json对象
- 然后使用nlohmann::json对象的成员函数 get<type(结构体名称)>() 将json字符串转换为对应结构体
这就是Nlohmann::JSON关于结构体(类)与JSON转换的基本教程