DynamicJsonDocument as instance member variable

Hello,

I have to say that I am not a C++ expert.
I am trying to create a class to read a config file.
For that I have defined my class Config.h as follows:

Config
{
  public:
    void readConfig();
  private:
    DynamicJsonDocument* _configJson;
};

The implementation of method readConfig looks like this:

void Config::readConfig() {
  _configJson = new DynamicJsonDocument(1024);
  *_configJson["jsonkey"] = "hello";
}

I tried a lot of versions now, but I always get errors like here:
error: invalid types 'ArduinoJson6172_91::DynamicJsonDocument* {aka ArduinoJson6172_91::BasicJsonDocument<ArduinoJson6172_91::DefaultAllocator>*}[const char [3]]' for array subscript

My assumptions was that it can't be sooo difficult to set the DynamicJson to a class member :frowning:

I hope someone can help me out...

Thanks, Roger

Your challenge is the you don't dereference the right thing. Check the C++ Operator Precedence

when you write

*_configJson["jsonkey"]

the compiler tried to get

_configJson["jsonkey"]

as a pointer and then applies the * operator to get its content.

that's not what you want to do: you need to first dereference your pointer and then apply the [] operator. Using parenthesis helps with this: [color=red]([/color]*_configJson[color=red])[/color]["jsonkey"]

this might help

#include <ArduinoJson.h>
DynamicJsonDocument* _configJson;

void setup() {
  Serial.begin(115200);
  _configJson = new DynamicJsonDocument(1024);
  (*_configJson)["jsonkey"] = "Hello World"; // **** note the ()
  if (_configJson->containsKey("jsonkey")) {
    Serial.println((const char*) (*_configJson)["jsonkey"]);  // **** note the ()
  }
}

void loop() {}

(run it with console opened at 115200 bauds)

1 Like

Hi J-M-L!
cool... that was the issue.
Thanks a lot,
Roger

:slight_smile: cool

have fun