使用 arduino-mqtt lib 解析 Json
Parsing Json using arduino-mqtt lib
我正在尝试使用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*
并调用sscanf
或strtol
或......来自己完成(,这不方便。最好改用 base-10 编码:
String json = "{"id" : 100 , "cmd" : 255}";
相关文章:
- 为C++编写JSON解析器
- 用于C++的 JSON 解析器
- 如何使用 Poco Json 解析器确定输入文档中错误的位置?
- 来自 Boost 的 JSON 解析器的警告 C4512 的解决方法
- 将 json 解析为数据模型 [是:C++头文件设计]
- 使用 rapidjson 从 json 解析操作列表
- Cpp:Cpp中的JSON解析器,提供支持序列化/反序列化功能,将JSON对象转换为用户定义的类
- Boost JSON解析器和IP地址
- 可以处理大输入(2GB)的JSON解析器
- C++提升 JSON 解析器抑制"No such node"输出
- C++将不同的JSON解析为一个结构或类
- 对 Boost JSON 解析器的调用永远不会返回
- 如何在 Blackberry Cascades 中创建用于 JSON 解析的列表视图
- Json解析使用rapidJson在c++中给出错误
- 哪些JSON解析库适合Google NaCl (c++)
- 如何使用c++语言和JSON解析器创建Restful Web服务
- Qt中的JSON类与c++中的其他JSON解析器
- 正确使用Poco c++ JSON解析数据
- 使用 Boost JSON 解析器时出现 JSON 格式设置错误
- 我如何使用json解析器的boost property_tree创建空数组节点