ProtoCore v0.0.1
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
Json - zero-heap JSON read and write

Layer: L6 Presentation ยท Build flags: none (core features only)

What this example teaches

The library's JSON support never allocates. JsonWriter formats into a fixed buffer you own, and json_get_str / json_get_int / json_get_bool read top-level members of a request body in place. This example builds a response with the writer and parses a request with the readers.

Building with JsonWriter. You hand it a stack buffer and call structural methods; it tracks nesting and overflow for you. Check ok() before sending - if the buffer was too small, ok() is false rather than truncating silently:

char buf[160];
JsonWriter w(buf, sizeof(buf));
w.begin_object();
w.kv_str("lib", "ProtoCore");
w.kv_uint("uptime_ms", (unsigned long)millis());
w.key("features"); w.begin_array(); w.str("json"); w.str("chunked"); w.end_array();
w.end_object();
if (w.ok()) server.send(slot_id, 200, "application/json", w.c_str());
else server.send(slot_id, 500, "text/plain", "json buffer overflow");
Builds a JSON document into a fixed caller buffer, no heap.
Definition json.h:59

Reading in place. The json_get_* readers scan the body for a top-level key and extract the value without copying the whole document or allocating a parse tree. Each returns whether the key was found:

char name[32]; long age = 0; bool admin = false;
bool have_name = json_get_str((const char *)req->body, "name", name, sizeof(name));
json_get_int((const char *)req->body, "age", &age);
json_get_bool((const char *)req->body, "admin", &admin);
bool json_get_str(const char *json, const char *key, char *out, size_t out_cap)
Read a top-level string member from a JSON object body.
Definition json.cpp:577
bool json_get_bool(const char *json, const char *key, bool *out)
Read a top-level boolean member (true/false) from a JSON object body.
Definition json.cpp:644
bool json_get_int(const char *json, const char *key, long *out)
Read a top-level integer member from a JSON object body.
Definition json.cpp:623

This is the proper tool for JSON bodies; the hand-rolled scanners in Advanced were just to show the mechanism.

Build and run

pio ci --board=esp32dev --project-option="framework=arduino" \
--lib="." examples/L6-Presentation/Json/Json.ino
curl http://<ip>/api/info
curl -X POST http://<ip>/api/echo -H "Content-Type: application/json" \
-d '{"name":"ada","age":36,"admin":true}'

Annotated source

The complete sketch (Json.ino), reproduced verbatim with added explanatory comments:

// Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
// SPDX-License-Identifier: AGPL-3.0-or-later
#include "protocore.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
PC server;
// GET /api/info - build a JSON object with JsonWriter (no heap).
void handle_info(uint8_t slot_id, HttpReq *req)
{
(void)req;
char buf[160];
JsonWriter w(buf, sizeof(buf)); // writes into this fixed buffer; tracks overflow
w.begin_object();
w.kv_str("lib", "ProtoCore");
w.kv_uint("uptime_ms", (unsigned long)millis());
w.kv_uint("free_heap", (unsigned long)ESP.getFreeHeap());
w.key("features"); // a key whose value is a nested array
w.begin_array();
w.str("json");
w.str("chunked");
w.str("middleware");
w.end_array();
w.end_object();
if (w.ok()) // false if the buffer overflowed
server.send(slot_id, 200, "application/json", w.c_str());
else
server.send(slot_id, 500, "text/plain", "json buffer overflow");
}
// POST /api/echo - read top-level fields from a JSON body and reflect them.
void handle_echo(uint8_t slot_id, HttpReq *req)
{
char name[32];
long age = 0;
bool admin = false;
// Each reader scans the body in place; returns whether the key was present.
bool have_name = json_get_str((const char *)req->body, "name", name, sizeof(name));
json_get_int((const char *)req->body, "age", &age);
json_get_bool((const char *)req->body, "admin", &admin);
char buf[128];
JsonWriter w(buf, sizeof(buf));
w.begin_object();
w.kv_str("name", have_name ? name : "");
w.kv_int("age", age);
w.kv_bool("admin", admin);
w.end_object();
server.send(slot_id, 200, "application/json", w.c_str());
}
void setup()
{
Serial.begin(115200);
init_wifi_physical(SSID, PASSWORD);
Serial.print("Connecting to WiFi");
while (!wifi_ready())
{
delay(250);
Serial.print('.');
}
uint32_t ip = pc_net_egress_ip(); // library egress IP (network byte order), no Arduino WiFi
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
server.on("/api/info", HttpMethod::HTTP_GET, handle_info);
server.on("/api/echo", HttpMethod::HTTP_POST, handle_echo);
int32_t result = server.begin(80);
if (result < 0)
{
Serial.printf("begin() failed (error %d)\n", result);
return;
}
Serial.println("Server started on port 80");
}
void loop()
{
server.handle();
}
Single-port HTTP server with deterministic, zero-allocation execution.
Definition protocore.h:348
void send(uint8_t slot_id, int code, const char *content_type, const char *payload)
Send an HTTP response with a body and close the connection.
int32_t begin(const WebServerConfig *cfg=nullptr)
Initialize all connection slots and open all registered listeners.
void on(const char *path, HttpMethod method, Handler callback)
Register a route handler.
void handle()
Drive the server - call every Arduino loop() iteration.
bool init_wifi_physical(const char *, const char *)
Connect to a WiFi access point.
Definition physical.cpp:41
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
Definition physical.cpp:77
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
Definition physical.cpp:45
Layer 1 (Physical) - link bring-up and live egress-interface reporting.
Layer 7 (Application) - public HTTP routing API.
@ HTTP_POST
Non-idempotent create / action.
@ HTTP_GET
Safe, idempotent read.
Fully-parsed HTTP/1.1 request.
uint8_t body[BODY_BUF_SIZE+1]
Stored body bytes, always null-terminated.