当前位置:网站首页>Rapidjson reading and writing JSON files

Rapidjson reading and writing JSON files

2022-07-04 07:18:00 object-oriented

#include "rapidjson/document.h"
#include "rapidjson/istreamwrapper.h"
#include "rapidjson/prettywriter.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/writer.h"
#include "rapidjson/filewritestream.h"

using namespace std;
using namespace rapidjson;

string readJsonfile(string path)
{
    ifstream config_file(path);
    if (!config_file.is_open())
    {
        return "json file not exist";
    }

    IStreamWrapper config(config_file);
    Document doc;
    doc.ParseStream(config);

    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    doc.Accept(writer);

    config_file.close();
    return buffer.GetString();
}

void writeToJsonFile(string &jsonstr, string filepath)
{
    Document doc;
    doc.Parse(jsonstr.c_str());

    FILE* fp = fopen(filepath.c_str(), "wb");
    char writeBuffer[65535];
    FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer));
    PrettyWriter<FileWriteStream> writer(os);
    doc.Accept(writer);
    fclose(fp);
    std::cout << "writeToJsonFile end" <<std::endl;
}

原网站

版权声明
本文为[object-oriented]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207040712453181.html