jsoncpp读写指定值封装
class CConfigJson:public Config
{
public:
CConfigJson(){}
CConfigJson(const std::string &strFileName);
std::string GetValue(std::string key) override;
int SetValue(std::string key, std::string value) override;
protected:
bool ReadJsonFile(const char *jsonFileName, Json::Value *jsonInfo);
bool WriteJsonFile(const char *jsonFileName, Json::Value *jsonInfo);
std::vector<std::string> split(std::string str, std::string pattern);
void ChangeValue(Json::Value& v, const std::vector<std::string>& vec, int n, std::string value);
private:
Json::Value root;
std::string m_strFileName;
};
cpp实现
CConfigJson::CConfigJson(const std::string &strFileName)
{
m_strFileName = strFileName;
ReadJsonFile(strFileName.c_str(), &root);
}
std::string CConfigJson::GetValue(std::string key)
{
Json::Value res = root;
std::vector<std::string> result = split(key, "/");
for (int k = 0; k < result.size(); k++)
{
res = res[result[k]];
}
return res.asString();
}
int CConfigJson::SetValue(std::string key, std::string value)
{
Json::Value& res = root;
std::vector<std::string> result = split(key, "/");
ChangeValue(res ,result, 0, value);
WriteJsonFile(m_strFileName.c_str(), &root);
return 0;
}
bool CConfigJson::ReadJsonFile(const char *jsonFileName, Json::Value *jsonInfo)
{
std::ifstream jsonFile(jsonFileName, std::ios::binary);
if (!jsonFile.is_open())
{
printf("OPEN %s ERROR\n", jsonFileName);
return false;
}
else
{
Json::Reader reader;
if (reader.parse(jsonFile, *jsonInfo))
{
jsonFile.close();
return true;
}
else
{
printf("parse json ERROR\n");
jsonFile.close();
return false;
}
}
return true;
}
bool CConfigJson::WriteJsonFile(const char *jsonFileName, Json::Value *jsonInfo)
{
Json::StyledWriter sw;
ofstream os;
os.open(jsonFileName, std::ios::out | std::ios::trunc);
if (!os.is_open())
cout << "error:can not find or create the file which named \" demo.json\"." << endl;
os << sw.write(*jsonInfo);
os.close();
return true;
}
std::vector<std::string> CConfigJson::split(std::string str, std::string pattern)
{
std::string::size_type pos;
std::vector<std::string> result;
str += pattern;
int size = str.size();
for (int i = 0; i < size; i++)
{
pos = str.find(pattern, i);
if (pos < size)
{
std::string s = str.substr(i, pos - i);
result.push_back(s);
i = pos + pattern.size() - 1;
}
}
return result;
}
void CConfigJson::ChangeValue(Json::Value& v, const std::vector<std::string>& vec, int n, std::string value)
{
if (n > vec.size())
{
return;
}
if (v.isMember(vec[vec.size() - 1]))
{
if (v[vec[vec.size() - 1]].isInt())
{
v[vec[vec.size() - 1]] = Json::Value(std::stoi(value));
}
else if (v[vec[vec.size() - 1]].isString())
{
v[vec[vec.size() - 1]] = Json::Value(value);
}
return;
}
else
{
ChangeValue(v[vec[n]], vec, n + 1, value);
}
}
示例
CCfgInstance::Get()->GetValue("aa/bb");
CCfgInstance::Get()->SetValue("aa/bb", "x");