Json Cpp isMember()总是返回True

Abh*_*del 3 c++ json

例如在简单的json中

{
    "A" :
    {
       "B" :
       {
         --something--
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个案例:

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

第二种情况:

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

知道First Case有什么问题吗?即使我x在isMember()电话前得到了.

Mat*_*zok 8

看看文档.

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. 
Run Code Online (Sandbox Code Playgroud)

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

  • 这也是STL映射中的标准行为. (3认同)