RapidJSON 如何在使用 FindMember 时接收成员对象

RapidJSON how to receive member object when using FindMember

我有 JSON,我想使用 FindMember 验证它然后接收它。 但问题是它确实找到了 "title" 字符串 但它不 return 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;
}

找到成员后,您可以简单地 return localMemberItr->value

但问题是,找不到成员return怎么办

一个可能的解决方案是return一个指针而不是引用。所以你可以 return &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
        }
    }
}