从JSON字符串创建rapidjson :: Value

时间:2015-09-23 23:41:31

标签: rapidjson

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

1 个答案:

答案 0 :(得分:3)

简单回答:返回类型应为rapidjson::Document而不是rapidjson::Value

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