说明
nlohmann实现了结构体与json自动互转。
下载
https://github.com/nlohmann/json.git
拷贝include/nlohmann/json.hpp到新建工程
例子
代码
#include <iostream>
#include "json.hpp"
#include <string>
using nlohmann::json;
using namespace std;
//普通结构体
struct tag1
{
std::string name;
int id;
float value;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(tag1,name,id,value)
};
//有业务逻辑的结构体
struct tagLogical
{
std::string name;
int id;
int type;
int value1;
int value2;
int value3;
//需要人工实现to_json();和from_json();
//其中本例中c++基础数据类型也可以使用对象类型
friend void to_json(nlohmann::json& j, const tagLogical& l)
{
j = nlohmann::json{
{"name",l.name},
{"id",l.id},
{"type",l.type}
};
if (l.type == 0)
{
j["value1"] = l.value1;
}
else if (l.type == 1)
{
j["value2"] = l.value2;
}
else if (l.type == 2)
{
j["value3"] = l.value3;
}
}
friend void from_json(const nlohmann::json& j, tagLogical& l)
{
if (j.contains("name")) j["name"].get_to(l.name);
if (j.contains("id")) j["id"].get_to(l.id);
if (j.contains("type")) j["type"].get_to(l.type);
if (l.type==0)
{
l.value1=j["value1"];
}
else if (l.type == 1)
{
l.value2 = j["value2"];
}
else if(l.type == 2)
{
l.value3 = j["value3"];
}
}
};
int main()
{
cout << "e.g.1" << endl;
tag1 t1;
t1.name = "aaa";
t1.id = 1;
t1.value = 1.1;
json j;
to_json(j,t1);
cout << j.dump() << endl;
std::string s = R"({"id":2,"name":"bbb","value":2.2})";
json j2=json::parse(s);
tag1 t2;
from_json(j2, t2);
cout << t2.name << " " << t2.id << " " << t2.value << endl;
//
{
cout <<endl<< "e.g.2" << endl;
tagLogical tagL;
tagL.name = "aaa";
tagL.id = 0;
tagL.type = 0;
tagL.value1 = 100;
json j;
to_json(j, tagL);
cout << j.dump() << endl;
std::string s = R"({"id":0,"name":"aaa","type":1,"value2":101})";
json j2 = json::parse(s);
tagLogical tagL2;
from_json(j2, tagL2);
cout << tagL2.name << " " << tagL2.id << " " << tagL2.type << " " << tagL2.value2 << endl;
}
}
输出
e.g.1
{"id":1,"name":"aaa","value":1.100000023841858}
bbb 2 2.2
e.g.2
{"id":0,"name":"aaa","type":0,"value1":100}
aaa 0 1 101
总结
1.c++中常用map设计程序。map可以用json表示,又使用nlohmann轻松完成json字符串与c++对象内存互转。
那么把map的c++代码写到.json配置文件中,避免密密麻麻一片代码的场景,技术支持又可以自定义维护。
2.以后有时间调研nlohmann的使用对继承与多态支持程度,能否避免人工实现的to_json();from_json();。
3.以后有时间查看nlohmann源码实现原理。