目前的Boost库为1.80,其中的Json工具使用示例如下:
//
// main.cpp
//
// Created by Tao on 2022/11/27.
//
#include <boost/json/src.hpp>
#include <iomanip>
#include <iostream>
namespace json = boost::json;
json::value parse_demo_str(std::string str) {
json::stream_parser p;
json::error_code ec;
p.write(str.c_str(), str.length(), ec);
if( ec )
return nullptr;
p.finish( ec );
if( ec )
return nullptr;
return p.release();
}
void pretty_print( std::ostream& os, json::value const& jv, std::string* indent = nullptr ) {
std::string indent_;
if(! indent)
indent = &indent_;
switch(jv.kind())
{
case json::kind::object:
{
os << "{\n";
indent->append(4, ' ');
auto const& obj = jv.get_object();
if(! obj.empty())
{
auto it = obj.begin();
for(;;)
{
os << *indent << json::serialize(it->key()) << " : ";
pretty_print(os, it->value(), indent);
if(++it == obj.end())
break;
os << ",\n";
}
}
os << "\n";
indent->resize(indent->size() - 4);
os << *indent << "}";
break;
}
case json::kind::array:
{
os << "[\n";
indent->append(4, ' ');
auto const& arr = jv.get_array();
if(! arr.empty())
{
auto it = arr.begin();
for(;;)
{
os << *indent;
pretty_print( os, *it, indent);
if(++it == arr.end())
break;
os << ",\n";
}
}
os << "\n";
indent->resize(indent->size() - 4);
os << *indent << "]";
break;
}
case json::kind::string:
{
os << json::serialize(jv.get_string());
break;
}
case json::kind::uint64:
os << jv.get_uint64();
break;
case json::kind::int64:
os << jv.get_int64();
break;
case json::kind::double_:
os << jv.get_double();
break;
case json::kind::bool_:
if(jv.get_bool())
os << "true";
else
os << "false";
break;
case json::kind::null:
os << "null";
break;
}
if(indent->empty())
os << "\n";
}
int main(int argc, char** argv) {
std::string str = R"+({
"pi": 3.141,
"happy": true,
"name": "Boost",
"nothing": null,
"answer": {
"everything": 42
},
"list": [1, 0, 2],
"object": {
"currency": "USD",
"value": 42.99
}
})+";
try {
// Parse the string as JSON
auto const jv = parse_demo_str(str);
// Now pretty-print the value
pretty_print(std::cout, jv);
} catch (std::exception const& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
使用解析器可以将一段字符串(模拟报文)解析为一个通用json value对象,再通过该对象来进行取值并进行打印查看。更多示例见后续更新。