ArduinoJson icon indicating copy to clipboard operation
ArduinoJson copied to clipboard

Help, JsonArray.add is acting like set only

Open augustoeliezer opened this issue 5 years ago • 1 comments

Any help? I have a class that serialize and deserialize from file, and another with the server.

Class Config(String filepath)
StaticJsonDocument<1000> doc;
save() => to file
load() => from file
Class ServerClass 
Config *config = new Config("file.json");

int ServerClass::add(JsonVariant &json) {

    JsonArray arr = config->doc.to<JsonArray>();
    arr.add(json); //its never add, only change the last array
    config->save();
    config->load(); //
    return json.size();
}

String ServerClass::list() {
    
    return config->toString(); //serializeJson(doc, str);
}

void ServerClass::api(AsyncWebServer *server) {


    AsyncCallbackJsonWebHandler *webapi = new AsyncCallbackJsonWebHandler("/api/someitem", [&](AsyncWebServerRequest *request, JsonVariant &json) {

        int count = this->add(json);
        Serial.println(count);
        request->send(200,"application/json", this->list());
    }
}

[Request] 1- {"item": 1, "name": "item1"} 2- {"item": 2, "name": "item2"}

[Response] 1- [{"item": 1, "name": "item1"}] Console: 1 2- [{"item": 2, "name": "item2"}] Console: 1 //Why?

file.json: {"item": 2, "name": "item2"}

[Expected] 1- [{"item": 1, "name": "item1"}] 2- [{"item": 1, "name": "item1"},{"item": 2, "name": "item2"}] file.json: [{"item": 1, "name": "item1"},{"item": 2, "name": "item2"}]

augustoeliezer avatar Apr 28 '21 22:04 augustoeliezer

I found my mistake, I use to, where must be as.

WRONG

JsonArray arr = config->doc.to<JsonArray>();

CORRECT

JsonArray arr = config->doc.as<JsonArray>();

augustoeliezer avatar Apr 29 '21 02:04 augustoeliezer