bst json

本文介绍如何使用Boost库中的Property Tree模块来解析和修改JSON文件。文中详细展示了创建JSON对象、写入文件、从字符串中读取JSON内容并进行修改的过程。此外,还提供了异常处理的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <boost/property_tree/ptree.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/json_parser.hpp>
using namespace boost::property_tree;

 

boost::property_tree::ptree ptree_root;
 ptree_root.put("root","me_root");


 boost::property_tree::ptree ptree_items;
 {
  boost::property_tree::ptree pt;  //一棵树
  pt.put<int>("item_1",20);
  pt.put<int>("item_2",40);
  ptree_items.push_back(make_pair("",pt));
 }


 {
  boost::property_tree::ptree pt;//又一棵树
  pt.put("item_1","30");
  pt.put("item_2","60");
  ptree_items.push_back(make_pair("",pt));
 }
 ptree_root.put_child("items", ptree_items );


 boost::property_tree::write_json("C:\\file_path.json",ptree_root);

 try
    {
        /*std::stringstream ss;
        ss << "{\"cmd\":\"19\",\"gwID\":\"00CD85462414\",\"devID\":\"695AA901004B1200\",\"type\":\"02\",\"data\":{\"status\":\"1\"}}";

        boost::property_tree::ptree pt;
  boost::property_tree::read_json(ss, pt);

  std::string cmd = pt.get<std::string>("cmd");
  std::string gwID = pt.get<std::string>("gwID");
  std::string devID = pt.get<std::string>("devID");
  std::string type = pt.get<std::string>("type");*/
  string s = "{\"age\" : 26,\"study\":{\"language\":{\"one\":\"chinese\",\"two\":\"math\"},\"fee\":500,\"subject\":[{\"one\":\"china\"},{\"one\":\"Eglish\"}]},\"person\":[{\"id\":1,\"name\":\"chen\"},{\"id\":2,\"name\":\"zhang\"}],\"name\" : \"huchao\"}";

  ptree pt;

  stringstream stream(s); //这步不知道为什么要这样

  read_json<ptree>( stream, pt);

  pt.put("study.language.one","physics");//修改数据(这步废了好久时间,最后通过读英文资料解决)

  pt.put("study.fee",600);

  string s1=pt.get<string>("age");

  cout<<s1<<endl;


    }
    catch (std::exception const& e)
    {
        std::cerr << e.what() << std::endl;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值