首页 > 解决方案 > ESP32 连接到 Weather API 以使用 JSON 数组获取信息

问题描述

所以,我正在尝试使用 ESP32 创建一个系统,该系统将来自网络服务器的信息收集到 ESP 中,但是我遇到了 Json 数组的问题。

这是我遇到问题的地方,在 Json 部分的开头:

WiFiClient client;
char servername[]="api.openweathermap.org";  //O servidor que estamos 
    // conectando para pegar as informações do clima
String result;

int  counter = 60;

String weatherDescription ="";
String weatherLocation = "";
String Country;
float Temperature;
float Humidity;
float Pressure;

void setup()
{
    Serial.begin(115200);

    //Conectando
    Serial.println("Connecting");
    WiFi.begin(ssid, password); //Conectar ao servidor WIFI

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
    }

    Serial.println("Connected");
    delay(1000);
}

void loop()
{
    if(counter == 60) //Get new data every 10 minutes
    {
        counter = 0;
        delay(1000);
        getWeatherData();
    }
    else
    {
        counter++;
        delay(5000);
    }
}

void getWeatherData() //função cliente para mandar/receber GET request data.
{
    if (client.connect(servername, 80)) {  //Começar conexão, chekar conexão
        client.println("GET /data/2.5/weather?id="+CityID+"&units=metric&APPID="+APIKEY);
        client.println("Host: api.openweathermap.org");
        client.println("User-Agent: ArduinoWiFi/1.1");
        client.println("Connection: close");
        client.println();
    } 
    else {
        Serial.println("connection failed"); //error message if no client connect
        Serial.println();
    }

    while(client.connected() && !client.available())
        delay(1); //Esperar pela data

    while (client.connected() || client.available()) { //Conectado ou Data disponivel
        char c = client.read(); //Pega Bytes do ethernet buffer
        result = result+c;
    }

    client.stop(); //stop client
    result.replace('[', ' ');
    result.replace(']', ' ');
    Serial.println(result);

    //Json part
    char jsonArray [result.length()+1];
    result.toCharArray(jsonArray,sizeof(jsonArray));
    jsonArray[result.length() + 1] = '\0';

    StaticJsonBuffer<1024> json_buf;
    JsonObject &root = json_buf.parseObject(jsonArray);
    //StaticJsonDocument<1024> json_buf;
    //deserializeJson(root, jsonArray);

    if (!root.success()) {

        Serial.println("parseObject() failed");
    }

    String location = root["name"];
    String country = root["sys"]["country"];
    float temperature = root["main"]["temp"];
    float humidity = root["main"]["humidity"];
    String weather = root["weather"]["main"];
    String description = root["weather"]["description"];
    float pressure = root["main"]["pressure"];

    weatherDescription = description;
    weatherLocation = location;
    Country = country;
    Temperature = temperature;
    Humidity = humidity;
    Pressure = pressure;

    Serial.println(weatherLocation);
    Serial.println(weatherDescription);
    Serial.println(Country);
    Serial.println(Temperature);
}

这是我遇到问题的地方:

//Json part
char jsonArray [result.length()+1];
result.toCharArray(jsonArray,sizeof(jsonArray));
jsonArray[result.length() + 1] = '\0';

StaticJsonBuffer<1024> json_buf;
JsonObject &root = json_buf.parseObject(jsonArray);
//StaticJsonDocument<1024> json_buf;
//deserializeJson(root, jsonArray);

if (!root.success()) {
    Serial.println("parseObject() failed");
}

String location = root["name"];
String country = root["sys"]["country"];
float temperature = root["main"]["temp"];
float humidity = root["main"]["humidity"];
String weather = root["weather"]["main"];
String description = root["weather"]["description"];
float pressure = root["main"]["pressure"];

错误:

StaticJsonBuffer is a class from ArduinoJson 5. Please see arduinojson.org/upgrade to learn how to 
upgrade your program to ArduinoJson version 6

我查看了文档,但没有任何成功。https://arduinojson.org/v6/doc/upgrade/

标签: jsonarduinowifiesp32

解决方案


重命名StaticJsonBufferStaticJsonDocument.

https://arduinojson.org/v6/doc/upgrade/状态

作为 JsonBuffer,JsonDocument 有两个版本。

第一个是StaticJsonDocument,相当于StaticJsonBuffer:

// ArduinoJson 5
StaticJsonBuffer<256> jb;

// ArduinoJson 6
StaticJsonDocument<256> doc;

StaticJsonDocumenthttps://arduinojson.org/v6/example/parser/有一个如何使用的示例

尝试:

StaticJsonDocument<1024> root;
deserializeJson(root, jsonArray);

推荐阅读