使用rapid json library编写json将删除所有缩进

6ioyuze2  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(91)

我正在使用rapid json https://rapidjson.org/阅读一个json文件,并使用windows应用程序上的cpp使用visual studio 2017将其写入另一个json文件。
文件阅读代码

FILE* fp = fopen(inputJson, "rb"); // non-Windows use "r" 
char readBuffer[65536];
FileReadStream is(fp, readBuffer, sizeof(readBuffer));
Document d;
d.ParseStream(is);
fclose(fp);

std::string json_str(readBuffer);

字符串
文件写入代码

FILE* fp2 = fopen(outputJson, "wb"); // non-Windows use "w" 
char writeBuffer[65536];
FileWriteStream os(fp2, writeBuffer, sizeof(writeBuffer));
Writer<FileWriteStream> writer(os);
d.Accept(writer);
fclose(fp2);


但在目标文件中,缩进全部丢失。
源文件

{
    "name" : "test_rapid",
    "rect_obj": 
    [
        {   "name": "high school mathematics",
            "price": 12,
            "fg_color": 
            {
                "input_type": "val_map_c",
                "input": 
                {   
                    "measname": "MetaData_eOrigin_c",
                    "values":  [0],
                    "mapping": ["white"],
                    "out_of_range" : "white"
                }
            }
        },


目标文件中的缩进丢失

{"name":"test_rapid","rect_obj":[{"name":"high school mathematics","price":12,"fg_color":{"input_type":"val_map_c","input":{


如何保持缩进?

amrnrhlw

amrnrhlw1#

为了保持缩进,需要使用PrettyWriter而不是Writer

FILE* fp2 = fopen(outputJson, "wb"); 
char writeBuffer[65536];
FileWriteStream os(fp2, writeBuffer, sizeof(writeBuffer));
PrettyWriter<FileWriteStream> writer(os);
writer.SetIndent(' ', 4);  // indent with 4 spaces
d.Accept(writer);
fclose(fp2);

字符串

相关问题