实例json:
{
"unicast" : "192.168.0.220",
"logging" :
{
"level" : "info",
"console" : "true",
"file" : { "enable" : "false", "path" : "/tmp/vsomeip.log" },
"dlt" : "false"
},
"applications" :
[
{
"name" : "client",
"id" : "0x1345"
}
],
"routing" : "server_clock",
"service-discovery" :
{
"enable" : "true",
"multicast" : "224.244.224.245",
"port" : "30490",
"protocol" : "udp"
}
}
头文件:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/foreach.hpp>
json解析:
boost::property_tree::ptree root;
try
{
boost::property_tree::read_json("E:/boost_demo/Project1/vsomeip.json", root);
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return -1;
}
路径不对或json文件格式错误会抛异常
获取key的value:
std::cout << root.get<std::string>("unicast") << std::endl;
//获取节点子节点的value
std::cout << root.get<std::string>("service-discovery.enable", "") << std::endl;
此处打印"192.168.0.220"和true, get函数如果节点不存在会抛异常,如果传入默认值" ",节点不存在不会抛异常
解析子节点:
boost::property_tree::ptree child = root.get_child("logging");//获取节点
for(boost::property_tree::ptree::const_iterator it = child.begin(); it != child.end(); ++it)//遍历子节点
{
std::cout << it->first << ": ";//获取子节点key
if(!it->second.empty())//判断是否还有子节点
{
std::cout << std::endl;
for(boost::property_tree::ptree::const_iterator ite = it->second.begin(); ite != it->second.end(); ++ite)//再次遍历
{
std::cout << " " << ite->first << ": " << ite->second.data() << std::endl;
}
}
else
{
std::cout << it->second.data() << std::endl;//没有则输出value
}
}
查找节点是否有名为xxx的子节点:
root.find(“unicast”) == root.not_found()
与not_found方法比较判断是否有名为unicast的子节点
put修改json节点:
root.put("unicast", "192.168.1.3");//修改节点属性,不存在则创建
root.put("unicast1.a", "192.168.1.4");
root.put("unicast1.b", "192.168.1.5");
boost::property_tree::write_json("E:/boost_demo/Project1/vsomeip.json", root);//写入到json文件
push_buck修改json节点:
boost::property_tree::ptree newt;
newt.put("t1", "2");
newt.put("t2", "3");
root.push_back(std::make_pair("new1", newt));
boost::property_tree::write_json("E:/boost_demo/Project1/vsomeip.json", root);
add_child修改json节点:
boost::property_tree::ptree neww;
neww.put("t3", "2");
neww.put("t4", "3");
root.add_child("new2", neww);
boost::property_tree::write_json("E:/boost_demo/Project1/vsomeip.json", root);
```