从 JSON 字符串创建 rapidjson::Value

Create a rapidjson::Value from a JSON string

我想从 JSON 字符串创建 rapidjson::Value,例如 [1,2,3]。注意:这不是一个完整的 JSON 对象,它只是一个 JSON 数组。在 Java 中,我可以使用 objectMapper.readTree("[1,2,3]") 从字符串创建 JsonNode

我完整的C++代码如下:

#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <iostream>

// just for debug
static void print_json_value(const rapidjson::Value &value) {
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    value.Accept(writer);

    std::cout << buffer.GetString() << std::endl;
}

//TODO: this function probably has a problem
static rapidjson::Value str_to_json(const char* json) {
    rapidjson::Document document;
    document.Parse(json);
    return std::move(document.Move());
}


int main(int argc, char* argv[]) {
    const char* json_text = "[1,2,3]";

    // copy the code of str_to_json() here
    rapidjson::Document document;
    document.Parse(json_text);
    print_json_value(document);  // works

    const rapidjson::Value json_value = str_to_json(json_text);
    assert(json_value.IsArray());
    print_json_value(json_value);  // Assertion failed here

    return 0;
}

谁能找出我函数中的问题str_to_json()

PS:上面的代码在 GCC 5.1.0 中有效,但在 Visual Studio Community 2015 中无效。

更新:

根据@Milo Yip的建议,正确的代码如下:

#include <rapidjson/document.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/writer.h>
#include <iostream>

static void print_json_value(const rapidjson::Value &value) {
    rapidjson::StringBuffer buffer;
    rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
    value.Accept(writer);

    std::cout << buffer.GetString() << std::endl;
}

static rapidjson::Document str_to_json(const char* json) {
    rapidjson::Document document;
    document.Parse(json);
    return std::move(document);
}


int main(int argc, char* argv[]) {
    const char* json_text = "[1,2,3]";

    // copy the code of str_to_json() here
    rapidjson::Document document;
    document.Parse(json_text);
    print_json_value(document);  // works

    const rapidjson::Document json_value = str_to_json(json_text);
    assert(json_value.IsArray());
    print_json_value(json_value);  // Now works

    return 0;
}

简单回答:return 类型应该是 rapidjson::Document 而不是 rapidjson::Value

更长的版本:Document 包含一个分配器,用于在解析期间存储所有值。当 returning Value(实际上是树的根)时,本地 Document 对象将被破坏,分配器中的缓冲区将被释放。它就像函数中的 std::string s = ...; return s.c_str();