由于对象中的对象,未收到 MQTT 消息

MQTT message is not received because of object in object

提问人:JorisVV 提问时间:5/13/2022 最后编辑:JorisVV 更新时间:5/15/2022 访问量:104

问:

图书馆:

<PubSubClient.h>
<ESP8266WiFi.h>
"ArduinoJson.h"

当我发送此 JSON 时,会收到消息,我可以用它做一些事情:

{"topic":"domoticz/out","payload":{"Battery":255,"LastUpdate":"2022-05-13 16:28:39","Level":25,"RSSI":12,"description":"","dtype":"Color Switch","hwid":"3","id":"00082007","idx":7,"name":"test5","nvalue":15,"stype":"RGBWWZ","svalue1":"25","switchType":"Dimmer","unit":1},"qos":1,"retain":false,"_msgid":"5d58bd06fd9025a4"}

但是当我发送此消息(有效负载对象中带有 Color 对象)时,没有任何反应,没有收到消息。

{"topic":"domoticz/out","payload":{"Battery":255,"Color":{"b":33,"cw":76,"g":77,"m":4,"r":187,"t":179,"ww":180},"LastUpdate":"2022-05-13 16:31:13","Level":37,"RSSI":12,"description":"","dtype":"Color Switch","hwid":"3","id":"00082007","idx":7,"name":"test5","nvalue":15,"stype":"RGBWWZ","svalue1":"37","switchType":"Dimmer","unit":1},"qos":1,"retain":false,"_msgid":"10c972aa25ee323b"}

这是回调函数:

 void callback(char *topic, byte *payload, unsigned int length) {
        Serial.print("Message arrived in topic: ");
        Serial.println(topic);
        StaticJsonDocument<1200> doc;
        //Deserialize the JSON document
        // DeserializationError error = 
        deserializeJson(doc, payload);
        int idx = doc["idx"];
        Serial.printf("       Idx: %d",idx);

我认为这是因为对象中有一个 Color 对象。有没有办法接收此消息?

Photo

编辑: 我剥离了JSON,现在在我的Arduino中收到了一条消息。但是我仍然不能使用 Color 对象变量。

{"Color":{"b":107,"cw":76,"g":238,"m":4,"r":227,"t":179,"ww":180},"Level":49,"idx":7,"nvalue":10,"svalue1":"49"}

试:

int t = doc["Color.t"];
Serial.printf(" t: %d",t);

没用

C++ JSON 对象 回调 MQTT

评论

2赞 ChrisMM 5/13/2022
您是否正在创建自己的反序列化?如果没有,您使用的是哪个库?“不起作用”是什么意思?
0赞 JorisVV 5/13/2022
问题全错了,我已经更新了
0赞 hardillb 5/14/2022
您需要显示函数的代码,并给出比“不起作用”更好的描述。callback
0赞 JorisVV 5/14/2022
使用回调更新了问题
0赞 hardillb 5/14/2022
尝试doc["Color"]["t"];

答:

0赞 JorisVV 5/14/2022 #1

要访问另一个对象中的对象,您需要两个步骤,因此需要“括号

int t = doc["Color"]["t"];
Serial.printf(" t: %d",t);