bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.7k stars 1.12k forks source link

deserializeJson from HTTP result in EmptyInput error #2073

Closed foskam closed 6 months ago

foskam commented 6 months ago

Description I tried everything. Deserialize using http.getString(), convert that to char*, using http.getStream... but always I get the EmptyInput error. When I send http.getString() to the serial it is not empty though... I want to get the JSON from this public webservice: http://worldtimeapi.org/api/timezone/Europe/Amsterdam

Troubleshooter's report

  1. The program uses ArduinoJson 7
  2. The issue happens at run time
  3. The issue concerns deserialization
  4. deserializeJson() returns EmptyInput
  5. Input comes from an HTTP response
  6. The status code is not in the list
  7. Increasing the timeout doesn't fix the issue
  8. The input is a String
  9. Passing a Stream to deserializeJson() doesn't fix the issue

Environment

Reproduction code

   HTTPClient client;
    //client.useHTTP10(true); tried with and without this line
    client.begin("http://worldtimeapi.org/api/timezone/Europe/Amsterdam");
    int httpCode = client.GET();
    if (httpCode > 0) {
      String payload = client.getString();      
      Serial.println(payload);  //this is showing JSON
      //payload.replace(" ","");  //tried cleaning up spaces etc.
      //payload.replace("\n","");
      //payload.trim();

      JsonDocument doc;     

      DeserializationError err = deserializeJson(doc, client.getStream()); 
                //also tried .getString, toCharArray 
      if (err) {
          Serial.print(F("deserializeJson() failed: "));
          Serial.println(err.c_str());
      }
   }
bblanchon commented 6 months ago

Hi @foskam,

client.getString() consumes the stream before deserializeJson() has a chance to read it. This explains why it returns EmptyInput.

Solution: remove the call to getString().

Best regards, Benoit

foskam commented 6 months ago

Thanks! That solved it… pretty logical now I think of it 😉

bblanchon commented 6 months ago

You're welcome, @foskam. Thank you for using ArduinoJson! Don't forget to cast a star to support the project :wink: