user63898
user63898

Reputation: 30905

RapidJSON how to receive member object when using FindMember

i have JSON which i want to validate it using FindMember and then receive it. but the problem is that it do find the "title" string BUT it do not return the 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;
}

Upvotes: 0

Views: 3683

Answers (1)

Milo Yip
Milo Yip

Reputation: 5072

You can simply return localMemberItr->value when the member was found.

But the problem is, what should it return when the member was not found.

A possible solution is to return a pointer instead of reference. So you can return &localMemberItr->value when the member was found, and nullptr (or 0) if it was not found.

In addition, by using JSON pointer it already has done what you did:

#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
        }
    }
}

Upvotes: 1

Related Questions