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];
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.
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));
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.
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.
bool json_get_int(const char *json, const char *key, long *out)
Read a top-level integer member from a JSON object body.
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:
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
void handle_info(uint8_t slot_id,
HttpReq *req)
{
(void)req;
char buf[160];
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");
w.begin_array();
w.str("json");
w.str("chunked");
w.str("middleware");
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");
}
void handle_echo(uint8_t slot_id,
HttpReq *req)
{
char name[32];
long age = 0;
bool admin = false;
bool have_name =
json_get_str((
const char *)req->
body,
"name", name,
sizeof(name));
char buf[128];
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);
Serial.print("Connecting to WiFi");
{
delay(250);
Serial.print('.');
}
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
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()
{
}
Single-port HTTP server with deterministic, zero-allocation execution.
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.
uint32_t pc_net_egress_ip(void)
IPv4 (network byte order) of the current egress interface, or 0 if none.
bool wifi_ready()
True if the WiFi station link is up (associated + an IP is assigned).
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.