This example shows how to implement an HTTP server that sends JSON document in the responses.

It uses the Ethernet library, but can be easily adapted for WiFi.

It sends the value of the analog and digital pins. The JSON document looks like the following:

  "analog": [0, 76, 123, 158, 192, 205],
  "digital": [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0]

Source code

#include <ArduinoJson.h>
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
EthernetServer server(80);

void setup() {
  // Initialize serial port
  while (!Serial) continue;

  // Initialize Ethernet libary
  if (!Ethernet.begin(mac)) {
    Serial.println(F("Failed to initialize Ethernet library"));

  // Start to listen

  Serial.println(F("Server is ready."));
  Serial.print(F("Please connect to http://"));

void loop() {
  // Wait for an incomming connection
  EthernetClient client = server.available();

  // Do we have a client?
  if (!client) return;

  Serial.println(F("New client"));

  // Read the request (we ignore the content in this example)
  while (client.available());

  // Allocate a temporary JsonDocument
  // Use to compute the capacity.
  StaticJsonDocument<500> doc;

  // Create the "analog" array
  JsonArray analogValues = doc.createNestedArray("analog");
  for (int pin = 0; pin < 6; pin++) {
    // Read the analog input
    int value = analogRead(pin);

    // Add the value at the end of the array

  // Create the "digital" array
  JsonArray digitalValues = doc.createNestedArray("digital");
  for (int pin = 0; pin < 14; pin++) {
    // Read the digital input
    int value = digitalRead(pin);

    // Add the value at the end of the array

  Serial.print(F("Sending: "));
  serializeJson(doc, Serial);

  // Write response headers
  client.println(F("HTTP/1.0 200 OK"));
  client.println(F("Content-Type: application/json"));
  client.println(F("Connection: close"));
  client.print(F("Content-Length: "));

  // Write JSON document
  serializeJsonPretty(doc, client);

  // Disconnect

Classes used in this example

Functions used in this example

Keep learning

Mastering ArduinoJson

The chapter “Serialize with ArduinoJson” of Mastering ArduinoJson is a tutorial to learn how to generate JSON documents with the library. It begins with a simple example, and then adds more features like serializing directly to a file or an HTTP client.