json库使用之Json::Path

9 篇文章 0 订阅

最近工作遇到了这样的一行代码: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了,然后写入文件。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值