JSON

JSONBufferWriter

Writes a JSON object to a buffer in RAM. You must pre-allocate the buffer larger than the maximum size of the object you intend to create.

JSONBufferWriter::JSONBufferWriter(char *buf, size_t size)

// PROTOTYPE
JSONBufferWriter(char *buf, size_t size);

// EXAMPLE - Clear Buffer
memset(buf, 0, sizeof(buf));
JSONBufferWriter writer(buf, sizeof(buf) - 1);

writer.beginObject();
writer.name("d").value(10.5);
writer.endObject();

Construct a JSONWriter to write to a buffer in RAM.

  • buf A pointer to a buffer to store the data. Must be non-null.
  • size Size of the buffer in bytes.

The buf is not zereod out before use.


// EXAMPLE - Null Terminate
JSONBufferWriter writer(buf, sizeof(buf) - 1);

writer.beginObject();
writer.name("d").value(10.5);
writer.endObject();
writer.buffer()[std::min(writer.bufferSize(), writer.dataSize())] = 0;

Instead of of zeroing out the whole buffer, you can just add the null terminator. A few things:

  • Pass sizeof(buf) - 1 to leave room for the null terminator.
  • You must use the expression std::min(writer.bufferSize(), writer.dataSize()) for the location to put the null terminator.

The reason is that writer.dataSize() is the size the data would be if it fit. It the data is truncated, then zeroing out at offset writer.dataSize() will write past the end of the buffer.

JSONBufferWriter::buffer()

// PROTOTYPE
char* buffer() const;

Returns the buffer you passed into the constructor.

JSONBufferWriter::bufferSize()

// PROTOTYPE
size_t bufferSize() const;

Returns the buffer size passed into the constructor.

JSONBufferWriter::dataSize()

// PROTOTYPE
size_t dataSize() const;

Returns the actual data size, which may be larger than bufferSize(). If the data is too large it is truncated, creating an invalid JSON object, but dataSize() will indicate the actual size, if the buffer had been big enough.