c++ - rapidjson 正确的 json 创建

标签 c++ json rapidjson

我正在尝试使用 rapidjson 创建一个 json,但在生成正确的输出时遇到了一些意想不到的问题。

我正在创建和填充这样的文档:

Document d;
d.SetObject();

rapidjson::Document::AllocatorType& allocator = d.GetAllocator();

size_t sz = allocator.Size();

d.AddMember("version",  1, allocator);
d.AddMember("testId",   2, allocator);
d.AddMember("group",    3, allocator);
d.AddMember("order",    4, allocator);

Value tests(kArrayType);
Value obj(kObjectType);
Value val(kObjectType);

obj.AddMember("id", 1, allocator);

string description = "a description";
val.SetString(description.c_str(), static_cast<SizeType>(description.length()), allocator);
obj.AddMember("description", val, allocator);

string help = "some help";
val.SetString(help.c_str(), static_cast<SizeType>(help.length()), allocator);
obj.AddMember("help", val, allocator);

string workgroup = "a workgroup";
val.SetString(workgroup.c_str(), static_cast<SizeType>(workgroup.length()), allocator);
obj.AddMember("workgroup", val, allocator);

val.SetBool(true);
obj.AddMember("online", val, allocator);

tests.PushBack(obj, allocator);
d.AddMember("tests", tests, allocator);

// Convert JSON document to string
rapidjson::StringBuffer strbuf;
rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(strbuf);
d.Accept(writer);

当我运行这段代码时,我期望获得这个 json:

{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": true
        }
    ]
}

但实际生成的输出是...

{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": tr{
    "version": 1,
    "testId": 2,
    "group": 3,
    "order": 4,
    "tests": [
        {
            "id": 1,
            "description": "a description",
            "help": "some help",
            "workgroup": "a workgroup",
            "online": true
        }
    ]
}

有什么想法吗?

最佳答案

最后,我设法将问题追溯到我在 VS 中使用 OutputDebugString 输出字符串的方式。如果我保存了结果字符串(由 GetString() 提供),输出结果如预期!

我被调试陷阱挫败了!

关于c++ - rapidjson 正确的 json 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35727691/

相关文章:

javascript - 如何使用 javascript For In 或 Object.keys 循环从 json 数组排序帖子

json - Spring @ReponseBody @RequestBody 与抽象类

java - 将 json 转换为对象

java - 从 JNI 调用返回阿拉伯语

c++ - Oracle OCCI - 按名称而不是索引获取列

c++ - 如何在 Wix 中将 $(var.Platform) 从 x86 更改为 Win32

c++ - Rapidjson::Type 的切换大小写

c++ - openssl libcrypto.a 和 libmysqlclient.a 关于 `ERR_remove_thread_state' 的多重定义

c++ - 使用 rapidjson 进行字符串化

c++ - 获取节点在rapidjson中的偏移量?