?
?
boost解析Json 版本1.77
新增json库包含头文件 #include<boost/json.hpp>
/*
boost::json::object 存放json对象
boost::json::array 存放json数组
boost::json::value 存放json数值
写入Json
添加对象
{
"name":"zhangSan",
"age":"12"
}
boost::json::object obj_;
obj_["name"] = "zhangSan";
obg_["age"] = "12";
std::cout << obj_ << std::endl;
-------------------------------------------------------------------分割线--------------------------------------------------------------
{
"name":[1,2,3,4,5]
}
boost::json::array arr_;
boost::json::object ob_;
arr_.push_back(1);
arr_.push_back(2);
arr_.push_back(3);
arr_.push_back(4);
ob_["name"] = arr_;
*/
写入JSON文件
#include <boost/filesystem/fstream.hpp>
#include <boost/json.hpp>
#include <boost/filesystem.hpp>
int main(void)
{
boost::filesystem::fstream os_;
os_.open(boost::filesystem::path("a.json"),std::ios_base::out);
if(!os_.is_open())
{
return 0;
}
boost::json::object obj;
boost::json::array arr;
obj["name"] = boost::json::value("ZhangSan");
obj["age"] = boost::json::value("12");
for(int i = 0; i < 10;i++)
{
arr.push_back(i);
}
obj["num"] = arr;
os_ << obj;
os_.close();
return 0;
}
读JSON文件
/*
假设文件格式位
{
"name":"zhangsan",
"age":"12",
"number":[1,2,3,4,5]
}
*/
#include <iostream>
#include <boost/json/parser.hpp>
#include <boost/json.hpp>
#include <boost/filesystem/fstream.hpp>
int main(void)
{
boost::filesystem::fstream in_;
in_.open(boost::filesystem::path("a.json"));
if(!in_.is_open())
{
return 0;
}
char buf[256];
std::string str;
while(!in_.eof())
{
in.getline(buf,sizeof(buf));
str.append(std::string(buf));
}
auto par = boost::json::parse(str);
for(auto &x : par.as_object())
{
std::cout << x.key() << std::endl;
std::cout << x.value() << std::endl;
}
in_.close();
return 0;
}
|