文章目录

  • JSON库基础
    • object
    • value
    • array
    • string
  • JSON使用
    • 构造JSON
    • 序列化
      • 对象序列化
    • 反序列化
      • 对象反序列化
      • 流输入

Boost很早就有了能解析JSON的库(Boost.PropertyTree)还能解析XML,INI和INFO等。但其笨重复杂。在1.75后引入了新的JSON解析库Boost.JSON。

JSON库基础

JSON中主要包括四种数据类型:object、value、array和string;要使用JSON功能,需要:

#include <boost/json.hpp>
using namespace boost::json;

从JSON字符串中获取键值(通过if_contains获取key对应value的指针,然后通过as_XXX获取实际值):

#include <boost/json.hpp>auto obj = boost::json::parse(recvContent).as_object();
auto opType = obj.at("TYPE").as_string();
auto pValue = obj.if_contains("OP_STR");
if (pValue)
{if (pValue->as_string().empty()){// ...}else{auto pStr = std::make_shared<std::string>(pValue->as_string().c_str());// ...}
}

object

object是JSON键值对的容器,定义在<boost/json/object.hpp>,其主要的成员函数:

Name Description
at(key) 获取指定Key对应的元素的引用(不存在时会抛出out_of_range异常)
begin/end 获取iterator
capacity 容量
cbegin/cend 获取const iterator
clear Erase all elements.
contains(key) 判断Key是否存在
count(key) 返回Key的数量
emplace Construct an element in-place.
empty 是否为空
erase(it/key) 根据key或iterator移除元素
find(key) 返回指定key的iterator或end()。
if_contains(key) 返回key对应value的指针,或null(不存在时)。
insert 插入元素
insert_or_assign 插入或赋值(若key已存在)
operator= Copy assignment.Move assignment.Assignment.
operator[] 存在返回对应引用,若不存在则插入null value,并返回
reserve 增加容量(若指定值小于现有容量,则什么也不做)
size 大小
swap Swap two objects.
max_size 静态成员,返回object能保存元素的最大数量。

value

表示JSON值的类型,主要的成员函数:

Name Description
as_array 若为数组,则返回对应的引用(array),否则抛出异常
as_bool
as_double
as_int64
as_object
as_string
as_uint64
类型匹配时,则返回对应的引用,否则抛出异常
at(key)
at(pos)
数组类型根据索引(从0开始),获取值引用;其他根据值返回引用;不存在时抛出异常
emplace_array
emplace_bool
emplace_double
emplace_int64
emplace_object
emplace_string
emplace_uint64
返回对应的引用,并修改value为对应类型(且赋为对应的默认值)
emplace_null Change the kind to null, discarding the previous contents.
get_array
get_bool
get_double
get_int64
get_object
get_string
get_uint64
获取对应类型的引用(不做任何检查,速度快)
if_array
if_bool
if_double
if_int64
if_object
if_string
if_uint64
类型匹配,返回对应的指针;否则返回nullptr
is_array
is_bool
is_double
is_int64
is_object
is_string
is_uint64
类型匹配,返回true
is_null Returns true if this is a null.
is_primitive Returns true if this is not an array or object.
is_structured Returns true if this is an array or object.
kind 返回值对应的底层类型
swap Swap the given values.
to_number Return the stored number cast to an arithmetic type.

array

JSON值为数组的类型,主要成员函数:

Name Description
at(pos) 获取指定索引(从0开始)处值的引用,出错抛出out_of_range异常
back 获取最后一个元素
begin/end
rbegin/rend
获取iterator
capacity 获取容量
clear 清空
data 获取底层数组的指针
emplace(pos, Arg&&) 在指定位置插入元素(构造)
emplace_back 在尾部插入元素
empty Check if the array has no elements.
earse 删除元素
front 返回第一个元素
if_contains Return a pointer to an element, or nullptr if the index is invalid.
insert Insert elements before the specified location.
operator= Copy assignment.Move assignment.Assignment.
operator[] Access an element.
pop_back 删除最后一个元素
push_back 在尾部添加元素
reserve 增加容量(若指定值小于现有容量,则什么也不做)
resize 修改元素数量(若比原来大则填充null value,否则删除多余元素)
shrink_to_fit Request the removal of unused capacity.
size Return the number of elements in the array.

string

字符串值类型,主要成员函数:

Name Description
append 追加字符(串)
assign 赋值
at 返回指定位置字符引用
back 返回最后一个字符引用
begin/end 返回iterator
c_str Return the underlying character array directly.
clear Clear the contents.
compare Compare a string with the string.
copy Copy a substring to another string.
data Return the underlying character array directly.
empty Check if the string has no characters.
ends_with Return whether the string end with a string.Return whether the string ends with a character.
erase Erase characters from the string.Erase a character from the string.Erase a range from the string.
find Find the first occurrence of a string within the string.Find the first occurrence of a character within the string.
find_first_not_of Find the first occurrence of any of the characters not within the string.Find the first occurrence of a character not equal to ch.
find_first_of Find the first occurrence of any of the characters within the string.
find_last_not_of Find the last occurrence of a character not within the string.Find the last occurrence of a character not equal to ch.
find_last_of Find the last occurrence of any of the characters within the string.
front Return the first character.
grow Increase size without changing capacity.
insert 插入
operator string_view Convert to a string_view referring to the string.
operator+= Append characters from a string.Append a character.
operator= Copy assignment.Move assignment.Assign a value to the string.
operator[] Return a character without bounds checking.
pop_back Remove the last character.
push_back Append a character.
replace 替换
reserve Increase the capacity to at least a certain amount.
resize Change the size of the string.
rfind Find the last occurrence of a string within the string.Find the last occurrence of a character within the string.
shrink_to_fit Request the removal of unused capacity.
size Return the number of characters in the string.
starts_with Return whether the string begins with a string.Return whether the string begins with a character.
subview Return a substring.

JSON使用

构造的JSON示例格式如下:

{"a_string": "test_string","a_number": 123,"a_null": null,"a_array": [1,"2",{"123": "123"}],"a_object": {"a_name": "a_data"},"a_bool": true
}

构造JSON

构造一个JSON很简单:定义一个object,然后设定各个value即可:

boost::json::object val;
val["a_string"] = "test_string";
val["a_number"] = 123;
val["a_null"] = nullptr;
val["a_array"] = {1, "2", boost::json::object({{"123", "123"}})
};
val["a_object"].emplace_object()["a_name"] = "a_data";
val["a_bool"] = true;

Boost.JSON支持使用std::initializer_list来构造,所以也可以这样使用:

boost::json::value val = {{"a_string", "test_string"},{"a_number", 123},{"a_null", nullptr},{"a_array", {1, "2", {{"123", "123"}}}},{"a_object", {{"a_name", "a_data"}}},{"a_bool", true}
};

使用initializer_list构造时,有时很难区分是数组还是对象,这是可以明确指定:

// 构造[["data", "value"]]
boost::json::value jsonAry = {boost::json::array({"data", "value"})};// 构造{"data": "value"}
boost::json::value jsonObj = boost::json::object({{"data", "value"}});

序列化

JSON对象可以使用serialize序列化:

std::cout << boost::json::serialize(val) << std::endl;

serializer还支持部分流输出(在数据量较大时,可以有效降低内存占用):

boost::json::serializer ser;
ser.reset(&val);
char temp_buff[10];
while (!ser.done()) {std::memset(temp_buff, 0, sizeof(char) * 10);ser.read(temp_buff, 9);std::cout << temp_buff << std::endl;
}

对象序列化

对象转换为JSON,Boost.JSON提供了一个非常简单的方法:只需要在需要序列化的类的命名空间中,定义一个重载函数tag_invoke(注意,是类所在的命名空间),然后通过value_from即可方便地序列化对象了:

namespace NSJsonTest {class MyClass {public:int a;int b;MyClass (int a = 0, int b = 1):a(a), b(b) {}};void tag_invoke(boost::json::value_from_tag, boost::json::value &jv, MyClass const &c) {auto & jo = jv.emplace_object();jo["a"] = c.a;jo["b"] = c.b;}MyClass myObj;auto jv = boost::json::value_from(myObj)
}

反序列化

通过boost::json::parse可方便地把字符串反序列化为JSON结构。

auto decode_val = boost::json::parse("{\"123\": [1, 2, 3]}");

在非严格模式下,Boost.JSON可以选择性的对一些不那么严重的错误进行忽略:

unsigned char buf[4096];
boost::json::static_resource mr(buf);
boost::json::parse_options opt;
opt.allow_comments = true;     // 允许注释
opt.allow_trailing_commas = true;  // 允许尾部逗号
boost::json::parse("[1, 2, 3, ] // comment test", ec, &mr, opt);
std::cout << ec.message() << std::endl;

对象反序列化

与对象序列化对应的是对象反序列化;也是在命名空间中定义个tag_invoke函数,然后即可通过value_to把JSON对象反序列化为类对象了:

MyClass tag_invoke(boost::json::value_to_tag<MyClass>, boost::json::value const &jv) {auto &jo = jv.as_object();return MyClass(jo.at("a").as_int64(), jo.at("b").as_int64());
}// jv为前面序列化时的对象
auto myObj = boost::json::value_to<MyClass>(jv);

流输入

通过stream_parser可以流的方式读入要解析的字符串:

boost::json::stream_parser p;
p.reset();
p.write("[1, 2,");
p.write("3]");
p.finish();
std::cout << boost::json::serialize(p.release()) << std::endl;

BOOST的JSON解析库Boost.JSON简介相关推荐

  1. C++的Json解析库:jsoncpp和boost

    JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org,本文不再对json做介绍,将重点介绍c++的j ...

  2. [转]C++的Json解析库:jsoncpp和boost

    JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org,本文不再对json做介绍,将重点介绍c++的j ...

  3. C++的Json解析库:jsoncpp和boost .

    JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org/,本文不再对json做介绍,将重点介绍c++的 ...

  4. C++的Json解析库:jsoncpp

    JSON(JavaScript Object Notation)跟xml一样也是一种数据交换格式,了解json请参考其官网http://json.org/,本文不再对json做介绍,将重点介绍c++的 ...

  5. iOS开源JSON解析库MJExtension

    iOS中JSON与NSObject互转有两种方式:1.iOS自带类NSJSONSerialization 2.第三方开源库SBJSON.JSONKit.MJExtension.项目中一直用MJExte ...

  6. gson解析天气json_几种常用JSON解析库性能比较

    PS:公众号推文时间工作日早晨8点50分,周末下午3点30分,不见不散哈! 作者:飞污熊 xncoding.com/2018/01/09/java/jsons.html 本篇通过JMH来测试一下Jav ...

  7. 深入 Go 中各个高性能 JSON 解析库

    深入 Go 中各个高性能 JSON 解析库 转载请声明出处哦~,本篇文章发布于luozhiyun的博客:https://www.luozhiyun.com/archives/535 其实本来我是没打算 ...

  8. 一个Json解析库的设计和实现

    一个Json解析库的设计和实现 一个Json解析库的设计和实现 设计思路 实现方法 1. 预处理(去除注释) 2. 词法分析 3. 语法分析 4. 树型优化 5. Json树构建 6. 后端处理 整体 ...

  9. Android学习之Json解析库Gson

    接着上一篇Volley,在使用Volley加载好数据之后,我们肯定不能直接使用这个数据,一般获取的数据都会是Json格式,所以自然而然我们要处理下Json,网络上有很多Json解析库,这里我使用Gso ...

  10. Unity的Json解析二–写Json文件

    本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接:http://blog.csdn.net/cartzhang/article/details/50378805 作者:car ...

最新文章

  1. 实战小课 | 深入剖析 「事件设计方法与规范」,夯实数据分析基础!
  2. Ie html button消失,input 按钮在IE下显现不一致的兼容问题
  3. JDK5--Annotation学习:基础(二)
  4. SpringBoot配置logback日志 (六)
  5. NuGet学习笔记001---了解使用NuGet给net快速获取引用
  6. UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position...的解决办法
  7. Socket编程项目VS开发环境配置
  8. 一个产品的风险预测怎么写_创业计划书中,项目风险评估怎么写?
  9. C语言圆角矩形画法,GDI+ 如何绘制圆角矩形(vc++)
  10. 非API接口限制介绍
  11. 全志A10平板上的ubuntu终极安装版,支持HDMI和平板本机LCD
  12. vant框架的输入框在IOS上出现输入空格不显示,需要在输入字符才展示问题
  13. 手机端宝贝描述中每张图片的宽要在480到1500之间,最大高度为2500, 以下图片不满足
  14. TCP通信常用的send,sendto,recv,recvfrom函数详解
  15. CodeM 第三题 世界杯
  16. win7 中使用NFS共享
  17. iOS逆向之某多多App抓包
  18. 智慧穿戴装置带动医疗大数据发展
  19. Qt 中的动画(Animations)
  20. ZJOI2006 物流运输

热门文章

  1. 腾讯云PCDN:从P2P到万物互联服务框架
  2. 微信小程序帮你赚到第一桶金
  3. 第13节 IIS之WEB服务器—用于发布网站
  4. PowerPoint中插入视频无法播放的问题
  5. 苹果safari浏览器video视频无法播放
  6. 华硕支持2003服务器主板,驱动天空 - 品牌主板 - 服务器主板 SERVER - 华硕服务器主板...
  7. MAVEN 引入jar包没问题,但是程序中使用jar中的类报错的坑
  8. 计算机网络协议 | 只有程序员才能读懂的西游记 | 让我这样学习简直就是一种享受~
  9. 大白话讲调度:非支配遗传算法与柔性作业车间调度
  10. lucas–kanade_Lucas–Kanade光流算法