JSON for Modern C++ 2.1.1
Loading...
Searching...
No Matches

◆ to_msgpack()

template<template< typename U, typename V, typename... Args > class ObjectType = std::map, template< typename U, typename... Args > class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template< typename U > class AllocatorType = std::allocator, template< typename T, typename SFINAE=void > class JSONSerializer = adl_serializer>
static std::vector< uint8_t > nlohmann::basic_json< ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer >::to_msgpack ( const basic_json< ObjectType, ArrayType, StringType, BooleanType, NumberIntegerType, NumberUnsignedType, NumberFloatType, AllocatorType, JSONSerializer > &  j)
inlinestatic

Serializes a given JSON value j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse.

Parameters
[in]jJSON value to serialize
Returns
MessagePack serialization as byte vector
Complexity\n Linear in the size of the JSON value j.
Example\n The example shows the serialization of a JSON value to a byte
vector in MessagePack format.
1#include <json.hpp>
2
3using json = nlohmann::json;
4
5int main()
6{
7 // create a JSON value
8 json j = R"({"compact": true, "schema": 0})"_json;
9
10 // serialize it to MessagePack
11 std::vector<uint8_t> v = json::to_msgpack(j);
12
13 // print the vector content
14 for (auto& byte : v)
15 {
16 std::cout << "0x" << std::hex << std::setw(2) << std::setfill('0') << (int)byte << " ";
17 }
18 std::cout << std::endl;
19}
static basic_json array(std::initializer_list< basic_json > init=std::initializer_list< basic_json >())
explicitly create an array from an initializer list
Definition json.hpp:2165
static std::vector< uint8_t > to_msgpack(const basic_json &j)
create a MessagePack serialization of a given JSON value
Definition json.hpp:7941
a class to store JSON values
Definition json.hpp:1040
basic_json<> json
default JSON class
Definition json.hpp:12369

Output (play with this example online):
0x82 0xa7 0x63 0x6f 0x6d 0x70 0x61 0x63 0x74 0xc3 0xa6 0x73 0x63 0x68 0x65 0x6d 0x61 0x00 

The example code above can be translated with
g++ -std=c++11 -Isrc doc/examples/to_msgpack.cpp -o to_msgpack 
See also
http://msgpack.org
from_msgpack(const std::vector<uint8_t>&, const size_t) for the analogous deserialization
to_cbor(const basic_json& for the related CBOR format
Since
version 2.0.9

Definition at line 7941 of file json.hpp.