使用RapidJSON写入JSON文件时,含\n的字符串未生成预期嵌套结构
RapidJSON写入嵌套JSON结构的问题修复
问题描述
我构造了一个带换行的JSON格式字符串jsonStr,代码如下:
string jsonStr = "{\n Enable : "; jsonStr += "1\n"; jsonStr += "test : "; jsonStr += "hello\n"; jsonStr += "}\n";
用cout打印时能正常显示嵌套JSON结构,但用RapidJSON的PrettyWriter写入文件时,jsonStr被当作普通字符串,其中的\n被转义,生成的文件内容如下:
{ "config": { "xxx": "{\n Enable : 1\n test : hello\n}\n" } }
试过用\\n替代\n,结果文件里直接出现\\n,问题没解决。预期生成的嵌套结构JSON应该是:
{ "config": { "xxx": { Enable : 1, test : hello } } }
当前写入代码:
void write_to_module_json_file(const string jsonStr, const string moduleName) { string jsonFile = getConfigName(moduleName)+".json"; Document d(kObjectType); Value data(kObjectType); Value value; value.SetString(jsonStr.c_str(), d.GetAllocator()); data.AddMember(rapidjson::StringRef(getConfigName(moduleName).c_str()), value,d.GetAllocator()); d.AddMember("config", data, d.GetAllocator()); FILE* fp = fopen(jsonFile.c_str(), "wb"); char writeBuffer[65536]; FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); PrettyWriter<FileWriteStream> writer(os); writer.SetIndent('\t',1); d.Accept(writer); fclose(fp); }
解决方案
核心问题是把JSON结构的字符串当成普通字符串值存入了RapidJSON文档,正确做法是先将jsonStr解析成RapidJSON的Value对象(即JSON对象),再添加到文档中。
修改后的代码如下:
#include <rapidjson/document.h> #include <rapidjson/writer.h> #include <rapidjson/filewritestream.h> #include <string> #include <cstdio> void write_to_module_json_file(const std::string& jsonStr, const std::string& moduleName) { std::string jsonFile = getConfigName(moduleName) + ".json"; // 1. 解析输入的jsonStr为RapidJSON文档对象 rapidjson::Document nestedDoc; nestedDoc.Parse(jsonStr.c_str()); if (nestedDoc.HasParseError()) { fprintf(stderr, "JSON解析错误: %s\n", rapidjson::GetParseError_En(nestedDoc.GetParseError())); return; } // 2. 构建主文档 rapidjson::Document d(rapidjson::kObjectType); rapidjson::Value data(rapidjson::kObjectType); // 3. 将解析后的嵌套JSON对象复制到主文档的Value中 rapidjson::Value nestedValue; nestedValue.CopyFrom(nestedDoc, d.GetAllocator()); data.AddMember(rapidjson::StringRef(getConfigName(moduleName).c_str()), nestedValue, d.GetAllocator()); d.AddMember("config", data, d.GetAllocator()); // 4. 写入文件 FILE* fp = fopen(jsonFile.c_str(), "wb"); if (!fp) { fprintf(stderr, "无法打开文件: %s\n", jsonFile.c_str()); return; } char writeBuffer[65536]; rapidjson::FileWriteStream os(fp, writeBuffer, sizeof(writeBuffer)); rapidjson::PrettyWriter<rapidjson::FileWriteStream> writer(os); writer.SetIndent('\t', 1); d.Accept(writer); fclose(fp); }
关键说明
- 调用
nestedDoc.Parse(jsonStr.c_str())将输入的JSON字符串解析为RapidJSON文档,使其被识别为JSON结构而非普通字符串。 - 解析后用
CopyFrom将嵌套文档内容复制到主文档的Value中,确保使用主文档的分配器管理内存(RapidJSON的内存管理依赖分配器)。 - 新增了解析错误和文件打开错误的处理逻辑,避免程序异常崩溃。
内容的提问来源于stack exchange,提问作者Suganya Sugumar
相关产品推荐
相关产品推荐

