How to use ArduinoJson with ArduinoMqttClient?
This page explains how to use ArduinoJson with ArduinoMqttClient, the official MQTT client library for Arduino. It shows how to use the JSON format in MQTT messages, but you can quickly adapt the examples to use MessagePack.
ArduinoMqttClient is quite new; if you have trouble, you should consider the more mature PubSubClient library.
Deserializing a JSON document in MQTT message
Once your program has received an MQTT message, you can call deserializeJson()
and pass the MqttClient
instance:
int messageSize = mqttClient.parseMessage();
if (messageSize) {
StaticJsonDocument<256> doc;
deserializeJson(doc, mqttClient);
// use the JsonDocument as usual...
}
This code leverages the Stream
interface implemented by MqttClient
, that’s why you don’t need to use a temporary buffer.
You can also use the same technique if you use a callback with MqttClient
:
void onMqttMessage(int messageSize) {
StaticJsonDocument<256> doc;
deserializeJson(doc, mqttClient);
// use the JsonDocument as usual...
}
Serializing a JSON document into an MQTT message
To publish a JSON document to an MQTT topic, you can use the Stream
interface or use a temporary buffer.
To use the Stream
interface, simply pass MqttClient
to serializeJson()
:
mqttClient.beginMessage(topic);
serializeJson(doc, mqttClient);
mqttClient.endMessage();
If you want to specify the size to beginMessage()
, you could use measureJson()
, but it’s faster to use a temporary buffer, like that:
char payload[64];
size_t payloadSize = serializeJson(doc, payload);
mqttClient.beginMessage(topic, payloadSize);
mqttClient.print(payload);
mqttClient.endMessage();