日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

BOOST的JSON解析库Boost.JSON简介

發布時間:2023/12/20 javascript 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 BOOST的JSON解析库Boost.JSON简介 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

文章目錄

  • 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>,其主要的成員函數:

NameDescription
at(key)獲取指定Key對應的元素的引用(不存在時會拋出out_of_range異常)
begin/end獲取iterator
capacity容量
cbegin/cend獲取const iterator
clearErase all elements.
contains(key)判斷Key是否存在
count(key)返回Key的數量
emplaceConstruct 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大小
swapSwap two objects.
max_size靜態成員,返回object能保存元素的最大數量。

value

表示JSON值的類型,主要的成員函數:

NameDescription
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_nullChange 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_nullReturns true if this is a null.
is_primitiveReturns true if this is not an array or object.
is_structuredReturns true if this is an array or object.
kind返回值對應的底層類型
swapSwap the given values.
to_numberReturn the stored number cast to an arithmetic type.

array

JSON值為數組的類型,主要成員函數:

NameDescription
at(pos)獲取指定索引(從0開始)處值的引用,出錯拋出out_of_range異常
back獲取最后一個元素
begin/end
rbegin/rend
獲取iterator
capacity獲取容量
clear清空
data獲取底層數組的指針
emplace(pos, Arg&&)在指定位置插入元素(構造)
emplace_back在尾部插入元素
emptyCheck if the array has no elements.
earse刪除元素
front返回第一個元素
if_containsReturn a pointer to an element, or nullptr if the index is invalid.
insertInsert 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_fitRequest the removal of unused capacity.
sizeReturn the number of elements in the array.

string

字符串值類型,主要成員函數:

NameDescription
append追加字符(串)
assign賦值
at返回指定位置字符引用
back返回最后一個字符引用
begin/end返回iterator
c_strReturn the underlying character array directly.
clearClear the contents.
compareCompare a string with the string.
copyCopy a substring to another string.
dataReturn the underlying character array directly.
emptyCheck if the string has no characters.
ends_withReturn whether the string end with a string.Return whether the string ends with a character.
eraseErase characters from the string.Erase a character from the string.Erase a range from the string.
findFind the first occurrence of a string within the string.Find the first occurrence of a character within the string.
find_first_not_ofFind 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_ofFind the first occurrence of any of the characters within the string.
find_last_not_ofFind the last occurrence of a character not within the string.Find the last occurrence of a character not equal to ch.
find_last_ofFind the last occurrence of any of the characters within the string.
frontReturn the first character.
growIncrease size without changing capacity.
insert插入
operator string_viewConvert 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_backRemove the last character.
push_backAppend a character.
replace替換
reserveIncrease the capacity to at least a certain amount.
resizeChange the size of the string.
rfindFind the last occurrence of a string within the string.Find the last occurrence of a character within the string.
shrink_to_fitRequest the removal of unused capacity.
sizeReturn the number of characters in the string.
starts_withReturn whether the string begins with a string.Return whether the string begins with a character.
subviewReturn 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简介的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。