mardi 5 octobre 2021

How to use JSON Response with IF Function

I have a requirement to match a JSON POST response by a ESP 8266.

My ESP8266 Code part is below,

  if (sub3 == "31") { //New User Registartion
        String data =  "{\"user_id\" :\"" + sub1 + "\",\"encrypted_password\" :\"" + sub2 + "\",\"option\" :\"" + sub3 + "\" ,\"request_datetime\" :\"" + currentDate + "\"}";
        String link1 = "http://" + server + ":" + String(port) + "/users/";
        HTTPClient http; //Declare object of class HTTPClient
        http.begin(wifiClient, link1);     //Specify request destination
        http.addHeader("Content-Type", "application/json");
        int httpCode = http.POST(data.c_str());
        Serial.println(currentDate);
        if (httpCode == 200) {
          String payload = http.getString();   //Get the response payload
          Serial.println(httpCode);   //Print HTTP return code
          Serial.println(payload);    //Print request response payload
          if (payload == "{\"Response\":\"Successful\"}") {
            link.read();
            Serial.println(F("Prompt other side Confirmation"));
            link.print("Successfuly_Registered");
            digitalWrite(statusLED, HIGH); //flash led to show data is arriving
            delay(20);
            digitalWrite(statusLED, LOW);
          }
          else {
            link.read();
            Serial.println(F("Prompt other side Error"));
            link.print("Error 1");
          }
...

When I received the response from backend to ESP8266 the IF statement if (payload == "{\"Response\":\"Successful\"}") { does not work,

Below is the response I am getting from the server when printed by Serial Monitor: enter image description here

It looks like IF statement failed and moved to else

else {
            link.read();
            Serial.println(F("Prompt other side Error"));
            link.print("Error 1");
          }

I want to know how to catch the JSON response correctly. TIA

Aucun commentaire:

Enregistrer un commentaire