写一个nodemcu接收并解析来自服务器的json信息的代码,并提供你代码引用的库文件来源
时间: 2024-06-12 07:03:25 浏览: 8
以下是一个示例代码,用于在NodeMCU上接收和解析来自服务器的JSON信息。它使用了ESP8266WiFi和ArduinoJson库。
```c++
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverAddress = "your_SERVER_ADDRESS";
const int serverPort = your_SERVER_PORT;
const int capacity = 1024; // the maximum size of JSON message
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
WiFiClient client;
if (client.connect(serverAddress, serverPort)) {
Serial.println("Connected to server");
client.print("GET /json HTTP/1.1\r\n");
client.print("Host: ");
client.print(serverAddress);
client.print("\r\n\r\n");
// read the JSON message
DynamicJsonDocument doc(capacity);
DeserializationError error = deserializeJson(doc, client);
if (error) {
Serial.print("Deserialization failed: ");
Serial.println(error.c_str());
} else {
Serial.println("JSON message received:");
serializeJsonPretty(doc, Serial); // print the JSON message to Serial monitor
// access JSON data
const char* name = doc["name"]; // get a string value
int age = doc["age"]; // get an integer value
bool isActive = doc["isActive"]; // get a boolean value
Serial.print("Name: ");
Serial.println(name);
Serial.print("Age: ");
Serial.println(age);
Serial.print("Is active: ");
Serial.println(isActive);
}
} else {
Serial.println("Connection failed");
}
delay(5000); // wait for 5 seconds before sending another request
}
```
ESP8266WiFi库可以在Arduino IDE的“工具”>“管理库”中安装。ArduinoJson库可以在https://arduinojson.org/上下载并手动添加到Arduino IDE中。