This page explains how to use ArduinoJson with PubSubClient, a popular MQTT library for Arduino. It shows how to use the JSON format in MQTT messages, but you can easily adapt the examples to use MessagePack instead.

Deserializing a JSON document in MQTT message

Once your program has subscribed to an MQTT topic, you can call deserializeJson() from the callback function.

void callback(char* topic, byte* payload, unsigned int length) {
  StaticJsonDocument<256> doc;
  deserializeJson(doc, payload, length);
  // use the JsonDocument as usual...
}

Note that you don’t need to cast the payload pointer because deserializeJson() supports byte* too.

Serializing a JSON document into an MQTT message

To publish a JSON document to an MQTT topic, you need to serialize it to a temporary buffer:

char buffer[512];
serializeJson(doc, buffer);
client.publish("outTopic", buffer);

You can save a few CPU cycles by passing the size of the payload to publish():

char buffer[512];
size_t n = serializeJson(doc, buffer);
client.publish("outTopic", buffer, n);

See also