使用 arduino-mqtt lib 解析 Json

Parsing Json using arduino-mqtt lib

本文关键字:Json 解析 lib arduino-mqtt 使用      更新时间:2023-10-16

我正在尝试使用arduino-mqtt lib。

我有这个工作发送 json 字符串。尝试使用 ArduinioJson 解析字符串时会出现问题。它只是不返回任何值。

我认为这可能与 mqttMessageRecived 函数(字符串和有效负载(中的指针引用有关。

出现 MQTT 消息时调用的函数:

void mqttMessageReceived(String &topic, String &payload){
//Example String for test
String json = "{"id" : "100" , "cmd" : "0xff"}";
jsonout(payload);
Serial.println("Sending Static String");
jsonout(json);

解析 json 输入的函数:

void jsonout(String Json){
StaticJsonDocument<200> doc;
//Deserialize the JSON document
DeserializationError error = deserializeJson(doc, Json);
Serial.println("Got String: ");
Serial.println(Json);
// Test if parsing succeeds.
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.c_str());
return;
}
const char* id = doc["id"];
const char* cmd = doc["cmd"];
// Print values.
Serial.println(id);
Serial.println(cmd);
}

非解析输出:来自 MQTT 的消息

Got String: 
"{"id" : 4 , "cmd": "0xee"}"

结果 = json 解析没有输出


非解析输出:发送静态字符串

Got String: 
{"id" : "100" , "cmd" : "0xff"}

结果 = json 解析的输出:

100 
0xff

问题是 - 在服务器的响应中

"{\"id\" : 4 , "cmd\": \"0xee\"}">

id字段是整数 - 不是字符数组。

所以你需要改变

const char* id = doc["id"];

int id = doc["id"];

(并更新测试字符串以使用 int 作为 ID(。

服务器返回一个id成员,这是一个Number "id":4,而你正在生成一个String "id":"200"id

您需要将代码调整为任一代码。如果它是一个数字(看起来是这样(,你需要发送"id":200并更改你的代码来获取一个数字:

unsigned id = (double)doc["id"];
// And to generate it:
String json = "{"id" : 100 , "cmd" : "0xff"}";

另外,对于 JSON,请注意十六进制编码,它没有转换为数字(您必须通过接收const char*并调用sscanfstrtol或......来自己完成(,这不方便。最好改用 base-10 编码:

String json = "{"id" : 100 , "cmd" : 255}";