解析来自串行窗口的 JSON 响应
parsing json response from serial window
嗨,我正在尝试从我的arduino中的网络服务器解析JSON响应,以便打开和关闭LED灯。我正在使用 wifi 客户端重复示例向我的服务器发出 get 请求:
http://arduino.cc/en/Tutorial/WiFiWebClientRepeating
这是我运行时从串行端口打印回来的内容
WiFiClient client;
char c = client.read();
Serial.write(c);
串口结果
connecting...
HTTP/1.1 200 OK
Date: Sun, 06 Apr 2014 01:14:37 GMT
Server: Apache
X-Powered-By: PHP/5.5.10
Cache-Control: no-cache
X-Frame-Options: SAMEORIGIN
Set-Cookie: expires=Sun, 06-Apr-2014 03:14:37 GMT; Max-Age=7200; path=/; httponly
Connection: close
Transfer-Encoding: chunked
Content-Type: application/json
19
{"lightstatus":"on"}
0
如何仅解析此响应的 JSON 部分,以便可以使用它来控制我的 LED?
谢谢
好吧,即使是JSON也"很难"解析arduino。因此,您应该考虑尽可能简单地使用响应,例如使用 1
/0
整数而不是"on"
。
你需要运行的,基本上是一个状态图:
if ('{' == client.read())
if ('"' == client.read())
if ('l' == client.read())
if ('i' == client.read())
if ('g' == client.read())
if ('h' == client.read())
if ('t' == client.read())
if ('s' == client.read())
if ('t' == client.read())
if ('a' == client.read())
if ('t' == client.read())
if ('u' == client.read())
if ('s' == client.read())
if ('"' == client.read())
if (':' == client.read()) {
char c = client.read();
if (c == '1')
// TURN LIGHT ON
else if (c == '0')
// TURN LIGHT OFF
}
这可以通过使用字符串并将状态保留在索引变量中来改进:
const char* VAL="{"lightstatus":"
int parse_value(char c) {
static int val_idx=0;
// end of parsing condition, the index reached string length
if (strlen(VAL) == val_idx) {
// if the value is '1', return >0, if the value is '0', return 0
if ('1' == c) return 1;
else if ('0' == c) return 0;
}
// otherwise let's check if we're still in string
if (c == VAL[val_idx]) {
// if we do, increment the index variable
++val_idx;
} else {
// or reset it
val_idx = 0;
}
// return -1 while we're still parsing the string
return -1;
}
要使用该代码,请执行以下操作:
char val=-1;
while (val < 0)
val = parse_value(Serial.read())
我没有测试它,但我希望你得到算法的想法!
呵呵
相关文章:
- 在c++中使用nlohmann从类到json的转换
- 如何在Qt窗口小部件中使用QStringView(或QStringRef)
- 问:如何使用C++中的按钮从窗口打开窗口
- C++json插入数组
- SDL 窗口不会弹出
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- nlohmann-json将一个数组插入到另一个数组中
- 如何在cpp文件之间切换窗口?在Qt中
- QuadTree只在窗口的右上角绘制
- 如何使用curlpp通过POST方法上传文件和json数据
- JSON转换为nlohmann JSON-lib中的结构数组
- VS Code "command":"make"与终端窗口中的命令行"make"不同
- NLOHMANN 的 JSON 库将数组转换为结构向量
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何在C++中找到active directory中禁用和锁定的窗口帐户
- 处理闪烁窗口事件
- 如何在 nlohmann 的 json 库中获取数组长度?
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- C++win32 API创建多个类似视口的窗口
- 解析来自串行窗口的 JSON 响应