3

I am getting a json object from aws iot MQTT. Assuming that json from aws is {status:opened}. Here is my code.

#include <ArduinoJson.h>
void messageHandler(char *topic, byte *payload, unsigned int length)
{
 StaticJsonDocument<32> doc;
 deserializeJson(doc, payload);
 const char *status = doc["status"];
 Serial.println(status);//opened
 if (status == "opened")
 {
 Serial.println("door is opened");//not excute
 }
 else if (status == "closed")
 {
 Serial.println("door is closed");
 }
}

Why the if condition is not being excute?

asked Jan 3, 2023 at 9:35
1
  • what's printed in the serial monitor? Commented Jan 3, 2023 at 16:00

1 Answer 1

6

That's one of the peculiarities of the C language: the == operator compares the string addresses, not their content. It makes sense when you think of them as pointers, but it can be confusing for beginners.

To fix this, you can use strcmp() like so:

if (strcmp(status,"opened") == 0)

Alternatively, you can change the type of status to JsonVariant, like so:

JsonVariant status = doc["status"]

It works with JsonVariant because I overloaded the == operator to support string comparison.

answered Jan 3, 2023 at 9:52
3
  • if (strcmp(status,"opened") == 0) You know probably knew this and just forgot, but for the benefit of anyone else, strcmp returns 0 for equality, and some negative and positive numbers for the other relative orderings. So, you'll want the == 0. Upvote. Commented Jan 3, 2023 at 15:46
  • Thanks, I updated the answer. Commented Jan 3, 2023 at 16:18
  • Disclaimer: I appreciate your work on this library. This and your answer are good and helpful. -- However, overloading operators in such a way is one of the many reasons I still dislike C++ after 40+ years of software development in many languages. It hides a lot of things up-front and (mis)leads to weird constructs, making it hard for non-experts to grasp good programming. C++ is therefore not an adequate programming language for beginners. Commented Jan 4, 2023 at 7:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.