ESPAsyncWebServer icon indicating copy to clipboard operation
ESPAsyncWebServer copied to clipboard

AsyncCallbackJsonWebHandler did not supports ArduinoJson 6+

Open nsnake opened this issue 2 years ago • 3 comments

When i works on ArduinoJson 6.19.4 with AsyncCallbackJsonWebHandler looks like

    AsyncCallbackJsonWebHandler *handler = new AsyncCallbackJsonWebHandler("/msg", [](AsyncWebServerRequest *request, JsonVariant &json)
                                                                           {
                                                                               JsonObject &jsonObj = json.as<JsonObject>();

                                                                               AsyncResponseStream *response = request->beginResponseStream("application/json");
                                                                               DynamicJsonBuffer jsonBuffer;
                                                                               JsonObject &root = jsonBuffer.createObject();
                                                                               root["code"] = 200;
                                                                               root["msg"] = "ok";
                                                                               root.printTo(*response);
                                                                               request->send(response);
                                                                           });

It will be many errors like that DynamicJsonBuffer is noly works on ArduinoJson 5.

Colud be supports ArduinoJson 6+ ? Thanks.

nsnake avatar Sep 15 '22 08:09 nsnake

+1

marchingband avatar Oct 25 '22 07:10 marchingband

Since I just stumbled upon that particular problem myself: ArduinoJson has deprecated JsonBuffer in favour of JsonDocument, which is a nicer/better abstraction. Also the printTo method was removed in favour of a global serializeJson method. See https://arduinojson.org/v6/doc/upgrade/ for more details.

The above code using the new API should look like this:

    AsyncCallbackJsonWebHandler *handler = new AsyncCallbackJsonWebHandler("/msg", [](AsyncWebServerRequest *request, JsonVariant &json)
       {
           JsonObject jsonObj = json.as<JsonObject>();

           AsyncResponseStream *response = request->beginResponseStream("application/json");
           DynamicJsonDocument jsonDoc(1024);
           JsonObject root = jsonDoc.to<JsonObject>();
           root["code"] = 200;
           root["msg"] = "ok";
           serializeJson(jsonDoc, *response);
           request->send(response);
       });

LongHairedHacker avatar Dec 20 '22 17:12 LongHairedHacker

[STALE_SET] This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.

stale[bot] avatar May 22 '23 01:05 stale[bot]