2

I am trying to retrieve JSON mqtt message I received in ESP32.

void mqttMsgCallback(char* topic, byte* payload, unsigned int length) {
    payload[length] = '\0';
    String _message = String((char*)payload);
    String _topic = String(topic);
    if (_topic.equals("Sys.GetInfo/"+getMacAddr()) == 1)
    {
      Serial.println("Message arrived for sys.GetInfo");
      StaticJsonDocument <256> msg1;
      Serial.println(_message);
      deserializeJson(msg1,_message);
      String callbackTopic = msg1["callbackTopic"];
      Serial.println(callbackTopic);
    }
}

The issue is when I publish mosquitto_pub -t "Sys.GetInfo/2462ABFC2CD0" -m "{"callbackTopic" : "1234"}" it works well like callbackTopic as 1234.

but when I publish mosquitto_pub -t "Sys.GetInfo/2462ABFC2CD0" -m "{"callbackTopic" : "xyz"}" it prints callbackTopic value as null. Please point me if I an missing something.

Arduino version 1.8.15 ArduinoJson : 6.18.2 Borad : ESP32

Thanks

4
  • 3
    Check the return value of deserializeJson() to see if it can even parse it as valid JSON. Maybe you need '{"callbackTopic" : "xyz"}' (single quotes round the outside) to preserve the quotes on the inside.
    – Majenko
    Aug 23 at 11:17
  • @Majenko it works when i publish like '{"callbackTopic" : "xyz"}'. Thanks why the message with "" works when callbackTopic value is numeric Aug 23 at 11:27
  • 1
    Probably because the value is numeric. 1234 is a valid "thing" - xyz isn't. "xyz" is, though, and if your shell is stripping the " because it's not either escaped or encapsulated within single quotes, then it can't parse xyz as a valid "thing".
    – Majenko
    Aug 23 at 11:32
  • payload[length] = '\0'; how do you know there is a length + 1 position available?
    – Juraj
    Aug 23 at 12:13
2

Your shell is stripping the " from inside the string. If you run the command:

$ echo "{"callbackTopic" : "xyz"}"

you get:

{callbackTopic : xyz}

so you see all the quotes are stripped. xyz isn't something that ArduinoJSON can parse. But 1234 is, so with the quotes stripped it's still considered valid.

You need to ensure the quotes aren't removed. There's two ways of doing this: escaping them, or encapsulating the string in single quotes which gives a more "literal" interpretation of the contents than double quotes:

Escaping:

"{\"callbackTopic\" : \"xyz\"}"

Single quotes:

'{"callbackTopic" : "xyz"}'

Either of those when used as a parameter to a command work - like:

$ echo '{"callbackTopic" : "xyz"}'
{"callbackTopic" : "xyz"}

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.