ArduinoJson can read data coming from either a buffer or a stream. I encourage you to use a stream because it consumes less memory and often leads to shorter programs; unfortunately, it’s harder to debug.
How to print the content of a stream
When you use a buffer, you can easily debug the input JSON document by writing it to the serial port. However, when you use a stream,
deserializeJson() consumes the input and doesn’t allow you to get a sneak peek at it. At least, not directly, we’ll need the help of another library.
We can print the content of the stream being consumed by using the
ReadLoggingStream class from the StreamUtils library.
This class is a decorator that adds the logging ability to any stream.
To construct a
ReadLoggingStream, you must pass the input stream (
File…) as the first argument, and the destination stream (
Serial, most likely) as the second argument.
Then, you can use the new instance in place of the original stream.
The following schema, taken from the documentation of StreamUtils, depicts the way data travels in
In Arduino, a
Stream is bidirectional: you can both write to it and read from it.
- The blue line (at the top) shows how data is written to the stream; it passes through the decorator unaltered.
- The orange line shows how data is read from the stream; it passes through the decorator, but it’s also copied to the logging stream (
Serialin most cases).
In other word, every byte that ArduinoJson pulls from the StreamUtils gets printed to the serial port.
For example, let’s say you’re reading a JSON document from a WiFi connection:
If you want to log the content of the JSON document to the serial port, you must replace this line with:
ReadLoggingStream loggingStream(wifiClient, Serial);
Of course, don’t forget to install the StreamUtils and to add
#include <StreamUtils.h> at the top of the file.