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.

On this page, we’ll see how to debug the input coming from a Stream, like EthernetClient, WifiClient, Serial, etc.

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 (WifiClient, EthernetClient, 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 ReadLoggingStream:

Flow of information in ReadLoggingStream

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 (Serial in most cases).

In other word, every byte that ArduinoJson pulls from the StreamUtils gets printed to the serial port.

Example

For example, let’s say you’re reading a JSON document from a WiFi connection:

deserializeJson(doc, wifiClient);

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);
deserializeJson(doc, loggingStream);

Of course, don’t forget to install the StreamUtils and to add #include <StreamUtils.h> at the top of the file.

StreamUtils is a powerful library that deserves more attention. Please give it a star to spread the word.

See also