问题描述
this is the error on serial monitor
我使用的是 ESP8266 NodeMcu,IDE 使用的是 Arduino
我不知道该怎么办,现在已经 10 个小时了。
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
//Provide your own WiFi credentials
const char* ssid = "Kyzer";
const char* password = "@kyzer4$";
//String for storing server response
String response = "";
//JSON document
DynamicJsonDocument doc(2048);
void setup() {
Serial.begin(115200);
//Initiate WiFi connection
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("WiFi connected with IP: ");
Serial.println(WiFi.localIP());
}
void loop() {
//Initiate HTTP client
HTTPClient http;
//The API URL
String request = "https://covid-api.mmediagroup.fr/v1/cases?country=Portugal";
//Start the request
http.begin(request);
//Use HTTP GET request
http.GET();
//Response from server
response = http.getString();
//Parse JSON,read error if any
DeserializationError error = deserializeJson(doc,response);
if(error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
delay(5000);
return;
}
//Print parsed value on Serial Monitor
Serial.print("cases: ");
Serial.println(doc["confirmed"].as<int>());
Serial.print("recovered: ");
Serial.println(doc["recovered"].as<int>());
Serial.print("deaths: ");
Serial.println(doc["deaths"].as<int>());
Serial.println("");
//Close connection
http.end();
//Wait five seconds
delay(5000);
}
请有人帮我我无法获得我想要的数据并在串行监视器上显示它,可能是什么问题?
解决方法
您尝试解析的 json 对象的结构如下:
{"All": {
"confirmed": 378656,"recovered": 304825,"deaths": 6254,"country": "Portugal","population": 10329506,"sq_km_area": 91982,"life_expectancy": "75.8","elevation_in_meters": 372,"continent": "Europe","abbreviation": "PT","location": "Southern Europe","iso": 620,"capital_city": "Lisboa","lat": "39.3999","long": "-8.2245","updated": "2020/12/22 23:22:35+00"
}
}
元素confirmed
、recovered
和deaths
都在All
元素下,因此您需要通过评估All
或使用{ {1}},或者创建一个名为 doc["All"]["confirmed"]
的新根 json 对象,以便您可以使用 All
访问它。看例子:
All["confirmed"]