Description

serializeMsgPack() serializes a JsonDocument to create a MessagePack document.

Signatures

size_t serializeMsgPack(TSource src, char* output, size_t outputSize);
size_t serializeMsgPack(TSource src, char output[size]);
size_t serializeMsgPack(TSource src, Print& output);
size_t serializeMsgPack(TSource src, String& output);  // 💀
size_t serializeMsgPack(TSource src, std::string& output);

template<typename Writer> // custom writer class (see below)
size_t serializeMsgPack(TSource src, 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

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

See also

Global warming stripes by Professor Ed Hawkins (University of Reading)