Can I parse data from a stream?
Yes.
Since ArduinoJson 5.8, parseArray()
and parseObject()
accept Arduino’s Stream
and std::istream
as input:
JsonObject& root = jsonObject.parseObject(myStream);
Parts of the input need to be copied into the JsonBuffer
, so you need to increase its capacity accordingly (the Assistant gives the required size).
The parser only copies the relevant parts of the input (it skips the spaces and the punctuation), so this is more efficient than copying the whole input in a char[]
before calling parseObject()
.
Example 1: SPIFFS
The following program parses a JSON document stored on SPIFFS:
// Initialize SPIFFS
SPIFFS.begin();
// Open the File (which implements Stream)
File file = SPIFFS.open("config.json", "r");
// Let ArduinoJson read directly from File
DynamicJsonBuffer jb;
JsonObject& config = jb.parseObject(file);
// We don't need the file anymore
file.close()
See a complete example in the chapter “Case Studies” of Mastering ArduinoJson.
Example 2: Serial
The following program parses a JSON document transmitted through the Serial port:
// Loop until there is data waiting to be read
while (!Serial.available())
delay(50);
DynamicJsonBuffer jb;
JsonObject& root = jb.parseObject(Serial);
See a complete example in the chapter “Case Studies” of Mastering ArduinoJson.
Example 3: EthernetClient
The following program parse a JSON document in an HTTP response using the Ethernet library:
EthernetClient client;
// Send request
client.connect(host, 80);
client.println(request);
// Skip response headers
char endOfHeaders[] = "\r\n\r\n";
client.find(endOfHeaders);
// Parse JSON object in response
DynamicJsonBuffer jb;
JsonObject& root = jb.parseObject(client);
See a complete example in the chapter “Case Studies” of Mastering ArduinoJson.
Example 4: HTTPClient
The following program parse a JSON document in an HTTP response using the ESP8266HTTPClient:
HTTPClient http;
// Send HTTP request
http.begin(url);
http.GET();
// Parse JSON object in response
DynamicJsonBuffer jb;
JsonObject& obj = jb.parseObjec(http.getStream());
See a complete example in the chapter “Case Studies” of Mastering ArduinoJson.
Example 5: SD card
The following program parses a JSON document stored on a SD card
// Initialize SD library
SD.begin(4);
// Open file
File file = SD.open(filename);
// Parse JSON object in file
DynamicJsonBuffer jb;
JsonObject& config = jb.parseObject(file);
// We don't need the file anymore
file.close()
See a complete example in the chapter “Case Studies” of Mastering ArduinoJson.