You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ESP8266使用Arduino_JSON库读取OpenWeatherMap JSON返回null求助

ESP8266解析OpenWeatherMap JSON返回null的解决方法

核心问题

你代码中访问myObject["weather"]["main"]的方式错误——示例JSON里的weather是数组类型(值被方括号[]包裹),直接通过键名访问数组会返回null,必须通过数组索引定位到具体元素后再访问字段。

解决步骤

  1. 修正weather字段的访问逻辑
    将myObject["weather"]["main"]改为myObject["weather"][0]["main"],因为OpenWeatherMap返回的weather数组中第一个元素就是当前天气信息。

  2. 额外排查要点

    • 先打印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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 22:02:36