提升JSON解析器和IP地址

时间:2017-09-22 12:28:41

标签: c++ json boost

我想获取具有ip地址的节点的子节点。 下面是我正在使用的参考JSON格式和代码。

{  
"nodes":{  
  "192.168.1.1": {  
     "type":"type1",         
     "info":"info1",
     "error":"error1"
  },
  "192.168.1.2":{  
     "type":"type2",         
     "info":"info2",
     "error":"error2"
  },
  "test":{  
     "type":"type2",         
     "info":"info2",
     "error":"error2"
  }
 }
}

以下是读取上面json数据的参考代码。

using boost::property_tree::ptree;
ptree pt;
std::string ttr("test.json");
read_json(ttr, pt);

BOOST_FOREACH(ptree::value_type &v, pt.get_child("nodes"))
{
    std::string key_ = v.first.data();
    std::string val_ = v.second.data();        

    boost::optional< ptree& > child = pt.get_child_optional( "nodes.192.168.1.1" );
    if( !child )
    {
        std::cout << "Child Node Missing.............." << std::endl; //Always shows Node Missing. How to deal with "." as key ?
    }
    else
        std::cout << "Child Node Not Missing.............." << std::endl;        
}

如果节点包含“。”,请您建议如何阅读该子节点。 ( IP地址 ) ?这里“nodes.test”将起作用,但“nodes.192.168.1.1”将无效,因为它包含“。”作为字符串?如何让它运作?

先谢谢。

1 个答案:

答案 0 :(得分:3)

来自docs

  

要使用默认'.'以外的分隔符,您需要显式构造路径对象。 ptree的路径类型是string_path实例化,因此引用它的最简单方法是ptree::path_type。这样,您可以使用其键中带点的树[。]

在你的情况下:

boost::optional< ptree& > child = pt.get_child_optional(ptree::path_type("nodes/192.168.1.1", '/'));
相关问题