我的arduino通过TCP接收到一个看起来像这样的json:
{"Order":9,"SenderID":"Master","Params":{"newSolution":"35"}}
我像这样使用#include <ArduinoJson.h>
来解析它:
void Connectivity::ProcessNewMessage(char* topic, byte* payload, unsigned int length)
{
StaticJsonDocument<80> doc;
DeserializationError err = deserializeJson(doc, payload);
if (err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.c_str());
}
else
{
//we get the Order, or 99 if Order is not set. JsonDeserializer never makes exceptions
//So the only way to know something was wrong is provide unexpected values as Order 99
int Order = doc["Order"] | 99;
switch(Order)
{
case 9:
{
//here I need to access the new solution that is
//in the Params.
const char* serializedParams = (const char*) doc["Params"];
Serial.println("testing 1:");
Serial.println(serializedParams);
Serial.println("++++1");
DeserializationError err = deserializeJson(doc, serializedParams);
if (err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.c_str());
}
else
{
//here the code when everything works
}
}
}
这是我运行东西时得到的输出:
---
internal: Message arrived [master/Arduino]
{"Order":9,"SenderID":"Master","Params":{"newSolution":"35"}}
testing 1:
++++1
deserializeJson() failed with code IncompleteInput`
您可以在传入的json中看到Params IS,但是在尝试访问它时为空。有任何想法吗 ??我是一位经验丰富的C#编码人员,但是C ++和所有char char * const char mess对我来说很老。。:)
答案 0 :(得分:0)
问题是我访问serializedParams的方式。此解决方案有效:
//incoming string is : {"Order":9,"SenderID":"Master","Params":{"newSolution":"35"}}
StaticJsonDocument<80> doc;
DeserializationError err = deserializeJson(doc, payload);
if (err) {
Serial.print(F("deserializeJson() failed with code "));
Serial.println(err.c_str());
}
else
{
const char* Params_newSolution = doc["Params"]["newSolution"];
// Params_newsOlution contains = "35"
float alreadyParsed = doc["Params"]["newSolution"];
// alreadyParsed contains 35.0
}