Json Cpp isMember()总是返回True

时间:2014-01-25 05:04:48

标签: c++ json

例如在简单的json中

{
    "A" :
    {
       "B" :
       {
         --something--
       }
    }
}

第一种情况:

json::Value root;
const Json::Value x = root["A"]["B"];
if (root.isMember("A")) --- always returns TRUE..

第二种情况:

Json::Value root;
If (root.isMember("A"))  ---- works fine
const Json::Value x = root["A"]["B"]; 

知道First Case有什么问题吗?即使我在x来电之前收到isMember()

1 个答案:

答案 0 :(得分:7)

看看documentation

Value &     operator[] (const char *key)
    Access an object value by name, create a null member if it does not exist. 
const Value &   operator[] (const char *key) const
    Access an object value by name, returns null if there is no member with that name. 
Value &     operator[] (const std::string &key)
    Access an object value by name, create a null member if it does not exist. 
const Value &   operator[] (const std::string &key) const
    Access an object value by name, returns null if there is no member with that name. 

基本上,您是在"A"电话上创建成员root["A"]。为了避免这种情况,请务必在实际访问该成员之前检查isMember(或仅在const对象上调用它,然后进行空检查 - 我会为前者做好准备。)