serializeMsgPack()
Description
serializeMsgPack()
serializes a JsonDocument
to create a MessagePack document.
Signatures
size_t serializeMsgPack(const JsonDocument& doc, char* output, size_t outputSize);
size_t serializeMsgPack(const JsonDocument& doc, char output[size]);
size_t serializeMsgPack(const JsonDocument& doc, Print& output);
size_t serializeMsgPack(const JsonDocument& doc, String& output); // 💀
size_t serializeMsgPack(const JsonDocument& doc, std::string& output);
template<typename Writer> // custom writer class (see below)
size_t serializeMsgPack(const JsonDocument& doc, Writer& output);
Arduino’s String
doesn’t allow nulls inside the string; don’t use this class for MessagePack documents.
The two first overloads support unsigned char
as well.
Arguments
doc
: theJsonDocument
to serialize (in fact, you can also use aJsonArray
, aJsonObject
, or aJsonVariant
)output
: the destination buffer where the result should be writtenoutputSize
: the capacity of the destination buffer
Because output
can be any implementation of Print
, you can uses instances like Serial
, EthernetClient
, WifiClient
…
Return value
serializeMsgPack()
returns the number of bytes written.
Performance
When you pass a Stream
to serializeMsgPack()
, it writes in small chunks, which can be slow depending on the target stream. For example, if you send to a WiFiClient
on an ESP8266, it will send many packets over the air, which is slow and inefficient. To improve speed and efficiency, we must send fewer, larger packets.
To write the MessagePack document in larger chunks, you can use WriteBufferingStream
from the StreamUtils library. See the example in serializeJson()
.
Custom writer
If none of the supported output types is suitable for you, you can implement a custom writer class. This class must implement two member functions, as shown below:
struct CustomWriter {
// Writes one byte, returns the number of bytes written (0 or 1)
size_t write(uint8_t c);
// Writes several bytes, returns the number of bytes written
size_t write(const uint8_t *buffer, size_t length);
};
Then, pass a reference to an instance of this class as the second argument of serializeMsgPack()
.
Example
JsonDocument doc;
doc["hello"] = "world";
serializeMsgPack(doc, Serial);
will write the following bytes to the serial output:
81 A5 68 65 6C 6C 6F A5 77 6F 72 6C 64