我有 JSON,我想使用 FindMember 验证它然后接收它。 但问题是它确实找到了“标题”字符串 但它不返回 rapidjson::Value
[{
"title" : "one",
"type" : "gg",
"center" : {
},
}]
rapidjson::Document document;
if(!document.Parse(jsonContent.c_str()).HasParseError())
{
if (document.IsArray())
{
for (rapidjson::SizeType i = 0; i < document.Size(); i++)
{
rapidjson::Value& findMemberInJsonNode = FindMemberInJsonNode(&document[i], "title");
}
}
}
rapidjson::Value& HelloWorld::FindMemberInJsonNode(rapidjson::Value* jsonValue,std::string str)
{
rapidjson::Value::MemberIterator localMemberItr = jsonValue->FindMember(str.c_str());
//create null
rapidjson::Value &val = rapidjson::Value::GenericValue();
if (localMemberItr != jsonValue->MemberEnd())
{
//IT IS ENTER HERE SO it DOES FIND THE "title" STRING
val = localMemberItr->value;
if (val.IsNull())
{
int s = 1;
}
else if (val.IsObject())
{
int s = 0;
}
}
//IT IS NULL
return val;
}
最佳答案
当找到成员时,您可以简单地返回 localMemberItr->value
。
但问题是,当找不到成员时,它应该返回什么。
一个可能的解决方案是返回一个指针而不是引用。因此,您可以在找到成员时返回 &localMemberItr->value
,如果找不到成员,则返回 nullptr
(或 0
)。
此外,通过使用 JSON pointer它已经完成了你所做的:
#include <rapidjson/pointer.h>
/* ... */
Pointer titlePointer("/title");
if (document.IsArray()) {
for (rapidjson::SizeType i = 0; i < document.Size(); i++) {
if (Value* title = titlePointer.Get(documents[i]) {
// "title" was found and the value is pointed by title
}
}
}
关于c++ - RapidJSON 如何在使用 FindMember 时接收成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816266/