我有一项任务是向来自C网站的请求发送JSON响应。我无法以正确的格式格式化响应。
基本上这是一个过程:用户点击网站上的“StopAll”按钮,我需要将所有设备的数据发回,作为一切已成功完成的响应。我知道原始数据和格式应该是什么样的......但我无法将其转换为“C”......
数据:
更新所有请求:
{powerStates: [true, false], startStates: [false, false], temperatures: [30, 40], macAddresses: ['11', '22'], status_code: 1}
我试过的代码:
if (client) {
Serial.println ("new client");
// An http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected ()) {
if (client.available ()) {
char c = client.read ();
buffer + = c;
Serial.write (c);
// If you've gotten to the end of the line (received a newline
// Character) and the line is blank, the http request has ended,
// So you can send a reply
if (buffer.indexOf ("true")> = 0 || buffer.indexOf ("false")> = 0) {
// You're starting a new line
client.println ("HTTP / 1.1 200 OK");
client.println ("Content-Type: application / json");
//client.println ();
client.println ("{\" powerStates \ ": [\" true \ ", \" true \ ", \" true \ "], \" startStates \ ": [\" false \ ", \" false \ " , \ "false \"], \ "temperatures \": [\ "444 \", \ "22 \", \ "33 \"], \ "macAddresses \": [\ "11-22-33-34 \ ", \" 11-22-33-35 \ ", \" 11-22-34-37 \ "], \" status_code \ ": 1}");
client.println ();
以上是响应代码.....但它不会更改网站上的任何数据。所以我不确定这个回复是否会进入网络。
有找到方法吗?
答案 0 :(得分:1)
如果只输出一个简单的JSON,则可以避免使用JSON库,只需使用printf即可。
#include <stdio.h>
#include <stdlib.h>
// Output simple fixed JSON data.
int main(int argc, char* *argv)
{
// Simulate your data as simply as possible
bool powerStates[2];
bool startStates[2];
int temperatures[2];
int macAddresses[2];
int status_code;
// Set your data
powerStates[0] = true;
powerStates[1] = false;
startStates[0] = false;
startStates[1] = false;
temperatures[0] = 30;
temperatures[1] = 40;
macAddresses[0] = 11;
macAddresses[1] = 22;
status_code = 1;
// Output JSON very simply
printf("{powerStates: [%s, %s], startStates: [%s, %s], temperatures: [%d, %d], macAddresses: ['%d', '%d'], status_code: %d}",
powerStates[0]?"true":"false",
powerStates[1]?"true":"false",
startStates[0]?"true":"false",
startStates[1]?"true":"false",
temperatures[0],
temperatures[1],
macAddresses[0],
macAddresses[1],
status_code = 1);
return 0;
}
如果您需要字符串而不是输出,只需更改为sprintf即可。