ESP32: Creating JSON messages

The objective of this post is to explain how to create JSON formatted messages using the ArduinoJson library and the ESP32.


Introduction

The objective of this post is to explain how to create JSON formatted messages using the ArduinoJson library and the ESP32. You can install this library via Arduino IDE libraries manager, as indicated in this previous post.

Note that the code will be very similar to the one in the post that explains how to create JSON messages for the ESP8266, which also uses the ArduinoJson library.


The code

First, we need to include the ArduinoJson library, in order to access all the functionality needed to create the JSON messages. Also, in order to be able to print the results, we need to open a serial connection. This will be done in the setup function and the rest of the code will be in the loop function.

#include <ArduinoJson.h>

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

Now, in the main loop, we need to declare an object of class StaticJsonBuffer, which will be used for creating the JSON message. As can be seen here, we need to specify the capacity of the buffer, in bytes, as a template parameter. Basically, the template parameter corresponds to the value we will put between <> in code we will see bellow.

We will be using 300 bytes, which is more than enough for the message we want to create. If you want this value specified in more detail, check this tool that helps with the calculation.

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

StaticJsonBuffer<300> JSONbuffer;
JsonObject& JSONencoder = JSONbuffer.createObject();

In this case, we want to create a JSON message that will match the structure shown bellow. In this case we are going to assign static values but we could get them from, for example, a sensor.

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

To create name/value pairs in the JSON structure, we use the subscript operator (square brackets), as shown in the code bellow. We will use this to specify that the “SensorType” is “Temperature”.

JSONencoder["sensorType"] = "Temperature";

To create arrays, we call the createNestedArray method on the JsonObject reference. This will return a reference to a JsonArray [1], which we will use to add the simulated sensor values. To do so, we simply call the add method on the JsonArray.

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

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

Now that we have the representation of our JSON message, we can print it to the serial console using different methods. We can use the printTo method of the JsonObject reference we defined early. We can directly pass the Serial connection object as input of this method for the content do be printed. In this case, it will print the JSON message with the less overhead possible.

If we need to print the content in a user friendly format, we can call the prettyPrintTo method, which will handle the indented formatting for us.

As an alternative, we can print the JSON message to a char buffer first, and only then print its content to the serial console. Check the 3 different ways bellow.

Serial.println("Less overhead JSON message: ");
JSONencoder.printTo(Serial);

Serial.println("\nPretty JSON message: ");
JSONencoder.prettyPrintTo(Serial);

Serial.println("\nPretty JSON message from buffer: ");
char JSONmessageBuffer[300];
JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
Serial.println(JSONmessageBuffer);

In case we need to get the size of the JSON message to print, we can call the measureLenght or the measurePrettyLength methods. These methods will return as output the size of the string produced by the printTo and prettyPrintTo, respectively.

Check the full source code bellow, with examples on how to use these two additional methods.

#include <ArduinoJson.h>

void setup() {

  Serial.begin(115200);
  Serial.println();

}

void loop() {

  Serial.println("—————");
  StaticJsonBuffer<300> JSONbuffer;
  JsonObject& JSONencoder = JSONbuffer.createObject();

  JSONencoder["sensorType"] = "Temperature";
  JsonArray& values = JSONencoder.createNestedArray("values");

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

  int lenghtSimple = JSONencoder.measureLength();
  Serial.print("Less overhead JSON message size: ");
  Serial.println(lenghtSimple);

  int lenghtPretty = JSONencoder.measurePrettyLength();
  Serial.print("Pretty JSON message size: ");
  Serial.println(lenghtPretty);
  Serial.println();

  Serial.println("Less overhead JSON message: ");
  JSONencoder.printTo(Serial);
  Serial.println();

  Serial.println("\nPretty JSON message: ");
  JSONencoder.prettyPrintTo(Serial);
  Serial.println();

  Serial.println("\nPretty JSON message from buffer: ");
  char JSONmessageBuffer[300];
  JSONencoder.prettyPrintTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  Serial.println(JSONmessageBuffer);
  Serial.println();

  delay(10000);

}


Testing the code

To test the code, just upload it to the ESP32 and open the Arduino IDE serial monitor. You should get an output similar to figure 1, which shows both the lengths of the messages and the JSON formatted content.

ESP32 Encoding JSON messages

Figure 1 – Output of the program, with the JSON formatted messages.


References

Technical details

  • ArduinoJson library: v5.9.0.
Advertisements
This entry was posted in ESP32 and tagged , , , , , , , , , . Bookmark the permalink.

One Response to ESP32: Creating JSON messages

  1. Pingback: ESP32: Sending JSON messages over MQTT | techtutorialsx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s