C++ 基于文件中的值初始化对象
我有以下JSON文件:C++ 基于文件中的值初始化对象,c++,json,class,C++,Json,Class,我有以下JSON文件: { "var": { "a": 1, "b": 2, "c": "a", "d" :3, "e" :"b", "f": 12, "g": 13, "h": 14 } } 我使用nlohmann的JSON库阅读了这篇文章。下面是一个工作示例,我手动读取JSON文件并使用它设置对象的成员变量: #include <iostre
{
"var": {
"a": 1,
"b": 2,
"c": "a",
"d" :3,
"e" :"b",
"f": 12,
"g": 13,
"h": 14
}
}
我使用nlohmann的JSON库阅读了这篇文章。下面是一个工作示例,我手动读取JSON文件并使用它设置对象的成员变量:
#include <iostream>
#include <fstream>
#include "json.hpp"
using namespace std;
class
Test
{
private:
public:
int a, b, d, f, g, h;
string c, e;
};
int main()
{
ifstream input_json("tmp.json");
nlohmann::json j = nlohmann::json::parse(input_json);
Test test;
test.a = j["var"]["a"];
test.b = j["var"]["b"];
test.c = j["var"]["c"];
test.d = j["var"]["d"];
test.e = j["var"]["e"];
test.f = j["var"]["f"];
test.g = j["var"]["g"];
test.h = j["var"]["h"];
return 0;
}
#包括
#包括
#包括“json.hpp”
使用名称空间std;
班
试验
{
私人:
公众:
int a,b,d,f,g,h;
字符串c,e;
};
int main()
{
ifstream输入_json(“tmp.json”);
nlohmann::json j=nlohmann::json::parse(输入_json);
试验;
测试a=j[“var”][“a”];
测试b=j[“var”][“b”];
测试c=j[“var”][“c”];
测试d=j[“var”][“d”];
test.e=j[“var”][“e”];
测试f=j[“var”][“f”];
test.g=j[“var”][“g”];
test.h=j[“var”][“h”];
返回0;
}
问题:假设我的JSON结构有+10个变量。有没有一种方法可以用我从JSON文件中读取的值自动初始化一个对象,或者必须像上面那样手动键入它?为什么不将代码放在
main
中的构造函数Test::Test(std::string filename)
,用a
或this->a
等替换test.a
?这就是你所说的自动化吗?除非JSON变量名有一个模式(例如,此处所示的完全字母顺序),否则我认为您必须至少编写一次这样的手动代码…std::map?如果C++没有本机反射,您可以使用一些库来允许添加反射性,然后编写通用代码。