最近工作遇到了这样的一行代码:Json::Value& table = Json::Path(name).make(config);
table = value; 一行注释也没有,一下子也看不出来啥意思,于是就有了这篇博文。
经过代码测试,Json::Path(name).make(config) 得到的是config 里的一个名为name的对象,因为table是引用,所以table = value 其实就是把名为name的对象重新赋值了,即config里的name对象已经修改了。
#include <json.h>
#include <fstream>
#include <iostream>
bool loadConfig(std::string &fileName, Json::Value &content);
void setConfig(std::string &fileName, Json::Value &value);
bool stringToJson(const std::string &data, Json::Value &json);
int main()
{
std::string fileName = "userAccount";
Json::Value config;
loadConfig(fileName, config);
std::string name("permissions");
Json::Value& table = Json::Path(name).make(config);
Json::Value newValue;
newValue["userCenter.modify"]["id"] = 200;
table = newValue;
setConfig(fileName, config);
return 0;
}
//加载文件内容到json中
bool loadConfig(std::string &fileName, Json::Value &content)
{
std::ifstream file(fileName, std::ios::in);
if(file.good())
{
file.seekg(0, std::ios::end);
size_t size = file.tellg();
file.seekg(0, std::ios::beg);
char *buf = new char[size];
file.read(buf, size);
std::string data(buf, size);
delete []buf;
stringToJson(data, content);
}
else
{
return false;
}
file.close();
return true;
}
//将json内容写入文件
void setConfig(std::string &fileName, Json::Value &value)
{
std::ofstream file(fileName, std::ios::out);
if(file.good())
{
std::string buf = value.toStyledString();
file.write(buf.c_str(), buf.length());
}
file.close();
}
//string 转 json
bool stringToJson(const std::string &data, Json::Value &json)
{
if(data.empty())
{
return false;
}
std::string err;
Json::CharReaderBuilder jsReader;
std::unique_ptr<Json::CharReader> reader(jsReader.newCharReader());
bool ret = reader->parse(data.c_str(), data.c_str() + data.length(), &json, &err);
return ret;
}
原始文件内容如下:
运行后文件内容如下:
上面的代码:
std::string name("permissions");
Json::Value& table = Json::Path(name).make(config);
Json::Value newValue;
newValue["userCenter.modify"]["id"] = 200;
table = newValue;
就是将原来的permissions对象替换为新的newValue了,然后写入文件。