我想从 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;
}
最佳答案
简单的回答:返回类型应该是 rapidjson::Document
而不是 rapidjson::Value
。
更长的版本:Document
包含一个分配器来存储解析期间的所有值。当返回 Value
(实际上是树的根)时,本地 Document
对象将被破坏,分配器中的缓冲区将被释放。这就像 std::string s = ...;在函数内返回 s.c_str();
。
关于rapidjson - 从 JSON 字符串创建 rapidjson::Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751187/