Skip to content

Get the length of a Serialized JSON #2213

@dirkx

Description

@dirkx

I often find situation where I'd like to know the length of the serialised output; and then usually do something like this:

           struct NullWriter {
                size_t write(uint8_t c) { return 1; };
                size_t write(const uint8_t *buffer, size_t length) { return length; };
            } _nullwriter;
            size_t len = serializeJson(jsonDoc, _nullwriter);

May be nice to have serializeJson(jsonDoc, NULL); be the equivalent for this.

As a background - here is a typical case were the custom writer really helps; but you need to have the length ahead o f time:

            PubSubClient _client; // MQTT client
           .... subscribe MQTT, etc...

            size_t len = serializeJson(jsonDoc, _nullwriter);

            if (_client.beginPublish("/foo/bar", len, false)) {
                struct PubSubWriter {
                    PubSubClient * _psc; 
                    size_t write(uint8_t c) { return _psc->write(c); };
                    size_t write(const uint8_t *buffer, size_t length) { return _psc->write(buffer,length); };
                } _pswriter = { ._psc = &_client };

                size_t actual = serializeJson(jsonDoc, _pswriter); 
                _client.endPublish();

                if (actual != len)
                        Log.printf("Only wrote %d bytes of a %d report to mqtt", actual, len);
            } else {
                        Log.printf("Could not post %d bytes to topic %s to mqtt", len, topic);
           };

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions