我需要检索 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
如何检索内部对象以继续解析?谢谢。
Edit:我需要的是获取内部对象的字符串表示形式,以便我可以调用另一个将解析它的函数。
Edit 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;
}
}
您需要手动迭代对象的成员,因为 GetString() 仅适用于字符串成员,而 document["a"] 是一个对象。您需要使用 MemberIterator 变量迭代该对象的成员。我已经超过 15 年没有使用 C* 了,所以我只能给出它应该如何工作的一般想法:
for (MemberIterator m = document["a"].MemberBegin(); m != document["a"].MemberEnd(); ++m) {
std::cout << m.name << " " << (m.IsNumber()?m.GetNumber():m.GetString()) << endl;
}
另外,您可能想看看 Accept() 方法,它似乎返回您给它的对象的 JSON 字符串。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)