1

I'd like my ESP8266 to provide some JSON endpoints. I want to use ArduinoJson for serialisation. While this works in general if I serialize into a String and return this String afterwards, I was wondering if there is really no way to do this without wasting so much memory. Shouldn't it be possible to do something like this? Any hints?

ESP8266WebServer server;
StaticJsonDocument<768> response;
response["night"] = _playback.isNight();
response["shuffle"] = _playback.isShuffle();
server.send_P(200, "application/json", NULL);
serializeJson(response, server.client());

(this gives the following error:)

no instance of overloaded function "serializeJson" matches the argument list -- argument types are: (ArduinoJson6141_0000010::StaticJsonDocument<768U>, WiFiServer::ClientType)
  • 1
    Did you look at the documentation of ArduinoJson? Did you try? Did it work? If not, what errors did you get? – Edgar Bonet Feb 10 at 17:41
  • Yes I did. Yes I tried. No it did not. I added the error message. – Nitek Feb 10 at 18:01
  • you can just build it as a string. imho, the big advantage of the json lib is parsing, not serializing. – dandavis Feb 10 at 18:32
  • Weird. WiFiServer::ClientType is defined as WiFiClient, which inherits from Client, which inherits from Stream, which inherits from Print, which you should be able to serialize to. Could you try to serialize to Serial, just to see if it works? – Edgar Bonet Feb 10 at 19:59
  • That’s what I thought! I serialized into a char[] and it works fine – Nitek Feb 10 at 20:12
2

serializeJson() accepts a Print&, i.e, a reference to a class that implements the Print interface.

WiFiClient does implement the Print interface, but serializeJson() cannot make a reference to it because ESP8266WebServer::client() returns a temporary. Indeed, C++ forbids references to temporary variables, only const reference to temporaries are allowed.

To fix this compilation error, you must extract a variable:

WiFiClient client = server.client();
serializeJson(doc, client);

The way I see it, ESP8266WebServer::client() should return a WiFiClient& instead of a WiFiClient, just as HTTPClient::getStream() does. I opened issue #7075 about that.

Anyway, even it this fixes the compilation, I'm not sure it will work as you intend because ESP8266WebServer may not allow writing directly to the WiFiClient.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.