JsonObject::printTo()
Description
Serializes the JsonObject
to create a minified JSON document.
If you want a prettified JSON document, use JsonObject::prettyPrintTo()
.
Signatures
size_t printTo(char* buffer, size_t size) const;
size_t printTo(char buffer[size]) const;
size_t printTo(Print &) const;
size_t printTo(String &) const;
size_t printTo(std::string &) const;
Arguments
The destination where the JSON document should be written. It can be either:
- a
buffer
with specifiedsize
(the size includes the zero-terminator), - an implementation of
Print
(likeSerial
,EthernetClient
…), - a
String
orstd::string
.
This function treats String
and std::string
as streams: it doesn’t replace the content, it appends to the end.
Return value
The number of bytes written.
How to view the JSON output?
When you pass a Stream
to JsonObject::printTo()
, it writes the JSON document to the stream but doesn’t print anything to the serial port, which makes troubleshooting difficult.
If you want to see what JsonObject::printTo()
writes, use WriteLoggingStream
from the StreamUtils library.
Performance
When you pass a Stream
to JsonObject::printTo()
, it sends the bytes one by one, which can be slow depending on the target stream. For example, if you send to a WiFiClient
on an ESP8266, it will send a packet over the air for each byte, which is terribly slow and inefficient. To improve speed and efficiency, we must send fewer, larger packets.
To write the JSON document in chunks, you can use WriteBufferingStream
from the StreamUtils library.
Example
StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.createObject();
object["hello"] = "world";
object.printTo(Serial);
will write the following string to the serial port:
{"hello":"world"}