I
I
Ihor Bratukh2019-11-09 23:28:33
Arduino
Ihor Bratukh, 2019-11-09 23:28:33

How to pass json buffer as function argument in ArduinoJson 6?

#include <Arduino.h>
#include <ArduinoJson.h> // @6.13.0

JsonDocument jsonParse(const String json, uint32_t buffer = 2048) {
    StaticJsonDocument<buffer> jsonBuffer;
    DeserializationError error = deserializeJson(jsonBuffer, json);

    if (error) {
        printToSerial(F("jsonParse error: "));
        printlnToSerial(error.c_str());
    }

    return jsonBuffer;
}

void setup() {
  const String json = F("{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}");
  JsonDocument document = jsonParse(json, 512);
  const String sensor = document[F("sensor")]; // "gps"
}

void loop() {}

On the 5th line, where the StaticJsonDocument<buffer> jsonBuffer;IDE (VSCode, PlatformIO) swears at buffer- the expression must have a constant value -- the value of the "buffer" parameter (declared on line 4) cannot be used as a constant
Question: How can buffer be passed as a function parameter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2019-11-10
@BRAGA96

It seems that here the size should be known at the compilation stage. It is easier to pass to the function not the size of the buffer, but let's say the buffer itself, or make the function a template parameter with the size of the buffer.
Your option with a variable is not suitable, because its value is not known at compile time.
You can also try DynamicJsonDocument , its size can be specified at runtime, according to the documentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question