使用RapidJSON检索JSON字符串中的嵌套对象 [英] Retrieving a nested object inside a JSON string using rapidjson
问题描述
我需要在JSON字符串中检索嵌套对象,而我正在尝试使用Rapidjson来实现.我发现的只是如何检索数组和基本类型,而不是子对象.我创建了以下玩具示例,该示例给出了错误:
I need to retrieve a nested object inside a JSON string and I'm trying to do it using rapidjson. All I've found is how to retrieve arrays and basic types, but not sub-objects. I have created the following toy example which gives an error:
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
如何检索内部对象以继续进行解析?谢谢.
How do I retrieve the inner object to continue my parsing? Thanks.
编辑:我需要获取内部对象的字符串表示形式,这样我才能调用另一个将对其进行解析的函数.
Edit: What I need is to obtain the string representation of the inner object so I can call another function that is going to parse it.
编辑2 :允许以字符串形式检索内部对象的代码:
Edit 2: code that allows to retrieve the inner object as a string:
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 *的实践,所以我只能大致了解它的工作方式:
You need to iterate through object's members manually, as GetString() only works on string members, while document["a"] is an Object. You need to iterate through that object's members using MemberIterator variable. I had no practice in C* for more than 15 years, so I can only give a general idea of how it should work:
for (MemberIterator m = document["a"].MemberBegin(); m != document["a"].MemberEnd(); ++m) {
std::cout << m.name << " " << (m.IsNumber()?m.GetNumber():m.GetString()) << endl;
}
此外,您可能希望查看Accept()方法,它似乎返回给定对象的JSON字符串.
Also, you might want to look at Accept() method, it seems to return a JSON string of an object you give it.
这篇关于使用RapidJSON检索JSON字符串中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!