ESP8266使用Arduino_JSON库读取OpenWeatherMap JSON返回null求助
ESP8266解析OpenWeatherMap JSON返回null的解决方法
核心问题
你代码中访问myObject["weather"]["main"]的方式错误——示例JSON里的weather是数组类型(值被方括号[]包裹),直接通过键名访问数组会返回null,必须通过数组索引定位到具体元素后再访问字段。
解决步骤
修正weather字段的访问逻辑
将myObject["weather"]["main"]改为myObject["weather"][0]["main"],因为OpenWeatherMap返回的weather数组中第一个元素就是当前天气信息。额外排查要点
- 先打印
jsonBuffer到串口,确认HTTP请求返回的JSON字符串完整、格式正确,没有截断或乱码 - 若返回的JSON数据较大,需确保Arduino_JSON库的缓冲区足够容纳,可检查库文档调整缓冲区大小
- 先打印
修改后的代码片段
jsonBuffer = httpGETRequest(serverPath.c_str()); myObject = JSON.parse(jsonBuffer); if (JSON.typeof(myObject) == "undefined") { Serial.println("Parsing input failed!"); return; } Serial.print("JSON object = "); Serial.println(myObject); lcd.clear(); int temp = int(myObject["main"]["temp"]); lcd.print(temp - 273); // 转换为摄氏度(更精准可写temp - 273.15) lcd.print("°C "); // 原代码打印"K"有误,此处修正为摄氏度标识 lcd.print(myObject["main"]["pressure"]); lcd.print("hPa "); lcd.print(myObject["main"]["humidity"]); lcd.print("%"); lcd.setCursor(0, 1); lcd.print(myObject["wind"]["speed"]); lcd.print("m/s "); // 修正weather字段的访问方式 lcd.print(myObject["weather"][0]["main"]);
内容的提问来源于stack exchange,提问作者Dragon
相关产品推荐
相关产品推荐

