最近写了一个格式化打印订单的项目,用到配置,希望比较轻量,正好程序处理的数据是json格式的,于是顺便用libjsoncpp做了一个配置文件解析。
而且整个项目可以直接以源文件方式添加到项目中, 跨平台做的比较不错。
Makefile
all:
g++ -static -o ./bin/jsonformat -g -O0 -I./libjsoncpp/include -I./libjsoncpp/src jsonformat.cpp \
libjsoncpp/src/json_reader.cpp \
libjsoncpp/src/json_writer.cpp \
libjsoncpp/src/json_value.cpp
配置文件config.json
{
"order":{
"header": "好哥餐厅 微信订单"
},
"usbprint":{
"printer": "Generic / Text Only"
}
}
主程序部分代码
#include <json/json.h>
void GetOrderHeader(const std::string & configpath, std::string & header)
{
std::ifstream myfile (configpath.c_str());
Json::Value root; Json::Reader reader;
if (reader.parse(myfile, root, false)){
header = root["order"].get("header", "").asString();
}
return ;
}
int main(int argc, char * argv[])
{
enum {MaxLineLen = 4000};
std::string szHeader = "";
char szPath [MaxLineLen] = "config.json";
GetOrderHeader(szPath, szHeader); if (szHeader.empty()) return -2;
return 0;
}