|
3 | 3 |  |
4 | 4 |
|
5 | 5 | # msgpack_cpp |
6 | | -C++ header-only msgpack library |
| 6 | +C++ header-only msgpack library that supports (de)serializing types directly, including custom types, as well as a dicitionary type `msgpackcpp::value` a la `nlohmann::json` or `boost::json::value`. |
7 | 7 |
|
8 | 8 | ## Examples |
9 | 9 |
|
@@ -143,6 +143,61 @@ int main() |
143 | 143 | } |
144 | 144 | ``` |
145 | 145 |
|
| 146 | +### Dictionary value |
| 147 | + |
| 148 | +```cpp |
| 149 | +#include "msgpack.h" |
| 150 | +#include "msgpack_sinks.h" |
| 151 | + |
| 152 | +const auto REQUIRE = [](auto res) {if (!res)throw std::runtime_error("bad");}; |
| 153 | + |
| 154 | +int main() |
| 155 | +{ |
| 156 | + using msgpackcpp::serialize; |
| 157 | + using msgpackcpp::deserialize; |
| 158 | + using msgpackcpp::sink; |
| 159 | + using msgpackcpp::source; |
| 160 | + |
| 161 | + // Data |
| 162 | + msgpackcpp::value jv0 = { |
| 163 | + {"pi", 3.141}, |
| 164 | + {"happy", true}, |
| 165 | + {"name", "Niels"}, |
| 166 | + {"nothing", nullptr}, |
| 167 | + {"answer", { |
| 168 | + {"everything", -42} |
| 169 | + }}, |
| 170 | + {"list", {1, 0, 2}}, |
| 171 | + {"object", { |
| 172 | + {"currency", "USD"}, |
| 173 | + {"value", 42.99} |
| 174 | + }} |
| 175 | + }; |
| 176 | + |
| 177 | + // Serialize (pack) |
| 178 | + std::vector<char> buf; |
| 179 | + auto out = sink(buf); |
| 180 | + jv0.pack(out); |
| 181 | + |
| 182 | + // Deserialize (unpack) |
| 183 | + msgpackcpp::value jv1; |
| 184 | + auto in = source(buf); |
| 185 | + jv1.unpack(in); |
| 186 | + |
| 187 | + // Check |
| 188 | + REQUIRE(jv1.is_object()); |
| 189 | + REQUIRE(jv1.size() == 7); |
| 190 | + REQUIRE(jv1.at("pi").as_real() == 3.141); |
| 191 | + REQUIRE(jv1.at("happy").as_bool() == true); |
| 192 | + REQUIRE(jv1.at("name").as_str() == "Niels"); |
| 193 | + REQUIRE(jv1.at("nothing").is_null()); |
| 194 | + REQUIRE(jv1.at("answer").at("everything").as_int64() == -42); |
| 195 | + REQUIRE(jv1.at("list").as_array().size() == 3); |
| 196 | + REQUIRE(jv1.at("object").at("currency").as_str() == "USD"); |
| 197 | + REQUIRE(jv1.at("object").at("value").as_real() == 42.99); |
| 198 | +} |
| 199 | +``` |
| 200 | +
|
146 | 201 | ## Installation |
147 | 202 |
|
148 | 203 | Just copy the contents of the include folder in your project with `msgpack_describe.h` as an optional header. |
|
0 commit comments