ESP8266: Encoding JSON messages

The objective of this post is to explain how to encode a JSON message using the ArduinoJson library.

Introduction

The objective of this post is to explain how to encode a JSON message in the ESP8266, using the ArduinoJson library. We assume that the ESP8266 libraries for the Arduino IDE were previously installed. You can check how to do it here.

Also, for previous posts about decoding JSON messages, check the Related Posts section in the bottom.

Setup

First of all, we will include the library that implements the parsing functionality. The library can be obtained via library manager of the Arduino IDE.

#include <ArduinoJson.h>

For debugging purposes, we start a serial communication in the setup function.

void setup() {
Serial.begin(115200);
Serial.println();
}

Main loop

As we would do to decode a JSON message (check here the previous post), we also declare an object of class StaticJsonBuffer for encoding. We need to specify a size that is big enough for the structure we are going to create. In this case, we specified 300 bytes.

StaticJsonBuffer<300> JSONbuffer;

Then, we get a reference to a JsonObject from the StaticJsonBuffer object we created, by calling the createObject method.

JsonObject& JSONencoder = JSONbuffer.createObject();

In this case, we want to create a JSON message that will match the structure we used in a previous post, which has a sensor type and an array of values simulating measures from that sensor. The structure we want to create is shown below.

{
"SensorType" : "Temperature",
"Value" : [20,21,23]
}

To create simple name/value pairs in the JSON structure, we use the subscript operator or, in other words, we use square brackets.

JSONencoder["sensorType"] = "Temperature";

To create arrays, we call the createNestedArray method on the JsonObject reference.

JsonArray& values = JSONencoder.createNestedArray("values");

Then we use the add method of the JsonArray reference to add the values we want on our array.

values.add(20);
values.add(21);
values.add(23);

Finally, we print the result to the serial connection, by using the printTo method of the JsonObject reference we defined early. We can directly pass the Serial connection to this method for the content do be directly printed. In this case, it will print the JSON message with the less overhead possible.

JSONencoder.printTo(Serial);

If we want to print the content indented, in a more user friendly format, we can call the prettyPrintTo method.

JSONencoder.prettyPrintTo(Serial);

Naturally, we can also print the JSON message to a char buffer first, and only then print it to the serial console.

If we need to know the size of the JSON message we are going to print, we just call the measureLenght method, or the measurePrettyLength method, on the JsonObject reference. This will return the size of the string produced by the printTo and prettyPrintTo methods, respectively.