config.json
{
"template_file": "templatecpp.txt",
"class_name": "ConfigLoad",
"config_name": "TestConfig",
"settingip_name": "ServerIp",
"file_name": "templatecpp.h"
}
templatecpp.txt
#include "rapidjson/reader.h"
#include "rapidjson/document.h"
#include <string>
using namespace rapidjson;
using namespace std;
class %(class_name)s
{
public:
static %(class_name)s &Instance()
{
static %(class_name)s instance;
return instance;
}
bool LoadJson(const std::string& jsonfile)
{
std::ifstream f(filename);
if(f.good())
{
std::stringstream buffer;
buffer << f.rdbuf();
Dom.Parse(buffer.str().c_str());
return true;
}
return false;
}
std::string GetIp()
{
rapidjson::Value& v = Dom["%(config_name)s"]["%(settingip_name)s"];
return v.GetString();
}
private:
Document Dom;
};
GenCode.py
# -*- coding: UTF-8 -*-
import json
import codecs
def main():
config = {}
with codecs.open("config.json", "r", "utf-8") as f:
config = json.loads(f.read())
if not config:
return
s = ""
template = config.get("template_file", "templatecpp.txt")
with codecs.open(template, "r", "utf-8") as f:
s = f.read()
if not s:
return
s = s % config
file = config["file_name"]
with codecs.open(file, "w", "utf-8") as f:
f.write(s)
f.flush()
if __name__ == '__main__':
main()
生成代码:
templatecpp.h
#include "rapidjson/reader.h"
#include "rapidjson/document.h"
#include <string>
using namespace rapidjson;
using namespace std;
class ConfigLoad
{
public:
static ConfigLoad &Instance()
{
static ConfigLoad instance;
return instance;
}
bool LoadJson(const std::string& jsonfile)
{
std::ifstream f(filename);
if(f.good())
{
std::stringstream buffer;
buffer << f.rdbuf();
Dom.Parse(buffer.str().c_str());
return true;
}
return false;
}
std::string GetIp()
{
rapidjson::Value& v = Dom["TestConfig"]["ServerIp"];
return v.GetString();
}
private:
Document Dom;
};