【发布时间】:2012-10-05 08:56:03
【问题描述】:
我需要在 JSON 字符串中检索一个嵌套对象,我正在尝试使用 rapidjson 来完成它。我发现的只是如何检索数组和基本类型,而不是子对象。我创建了以下给出错误的玩具示例:
rapidjson::Document document;
std::string test = " { \"a\": { \"z\" : 21 } } ";
std::cout << test << std::endl;
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
std::cout << "Parsing error" << std::endl;
} else {
if ( document[ "a" ].IsObject() ) {
std::cout << "OK" << std::endl;
std::cout << document[ "a" ].GetString() << std::endl;
}
}
这是执行时的输出:
{ "a": { "z" : 21 } }
OK
JSONTest: ../rapidjson/document.h:441: const typename Encoding::Ch* rapidjson::GenericValue<Encoding, Allocator>::GetString() const [with Encoding = rapidjson::UTF8<char>, Allocator = rapidjson::MemoryPoolAllocator<rapidjson::CrtAllocator>]: Assertion `IsString()' failed. Aborted
如何检索内部对象以继续解析?谢谢。
编辑:我需要的是获取内部对象的字符串表示,这样我就可以调用另一个函数来解析它。
编辑 2:允许将内部对象检索为字符串的代码:
rapidjson::Document document;
std::string test = "{\"a\":{\"z\":21}} ";
if ( document.Parse<0>( test.c_str() ).HasParseError() ) {
std::cout << "Error parsing" << std::endl;
} else {
if ( document[ "a" ].IsObject() ) {
rapidjson::StringBuffer sb;
rapidjson::Writer<rapidjson::StringBuffer> writer( sb );
document[ "a" ].Accept( writer );
std::cout << sb.GetString() << std::endl;
}
}
【问题讨论】:
-
是不是说RapidJson不支持分层对象?所以它只解析根级别?!?!
-
是edit2对递归很有用,可以将内部的json对象转成字符串,可以递归解析。