javascript
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>,其主要的成員函數:
| 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值的類型,主要的成員函數:
| 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值為數組的類型,主要成員函數:
| 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
字符串值類型,主要成員函數:
| 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简介的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国配电自动化设备市场趋势报告、技术动态
- 下一篇: 初学者的R markdown设置