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

ESP32-S3 Feather使用readStringUntil()读取字符串末尾带null的问题

解决ESP32-S3 Feather读取文件时字符串末尾带"null"的问题

问题根源分析

你代码中的serializeJson(doc, buffer)调用是导致"null"后缀的直接原因,结合你描述的现象(其他ESP32板正常),大概率和ArduinoJson版本差异或API使用错误有关:

  1. API误用:serializeJson的作用是将JsonDocument对象序列化为字符串,而非解析字符串到JsonDocument。你当前的代码中,doc是清空状态(每次循环后调用doc.clear()),所以serializeJson(doc, buffer)会将空文档序列化为"null",并写入buffer。
  2. 版本差异:ArduinoJson v5和v6对String类型的处理不同——v5中serializeJson会追加内容到现有String,而v6会覆盖原有内容。如果你的ESP32-S3使用v5,其他板用v6,就会出现这种现象:v5下"null"被追加到读取的JSON行末尾,而v6下直接覆盖成"null"(但你说其他板正常,说明其他板上这段代码可能没触发问题,或者你在其他板上实际用的是deserializeJson)。

解决方案

根据你的需求(仅需将保存的JSON发送到数据库,无需修改内容),最简单的修复方式是移除不必要的JsonDocument操作:

修改readLinesSD函数如下:

void readLinesSD(fs::FS &fs, const char *path)
{
  File file = fs.open(path);
  WiFiClient client;
  HTTPClient http;
  http.begin(client, serverName);
  http.addHeader("Content-Type", "application/json");
  
  if (!file)
  {
    Serial.println("Failed to open file for reading");
    return;
  }
  
  while (file.available())
  {
    String buffer = file.readStringUntil('\n');
    // 移除serializeJson和doc相关代码,直接使用读取到的buffer
    Serial.println(buffer);
    int httpResponseCode = http.POST(buffer);
    Serial.println(httpResponseCode);
    delay(200);
  }
  
  http.end();
  file.close();
}

如果你确实需要解析JSON进行验证或修改,应使用deserializeJson替代serializeJson:

void readLinesSD(fs::FS &fs, const char *path)
{
  File file = fs.open(path);
  WiFiClient client;
  HTTPClient http;
  http.begin(client, serverName);
  http.addHeader("Content-Type", "application/json");
  JsonDocument doc; // 建议将doc声明在函数内部,避免全局变量问题
  
  if (!file)
  {
    Serial.println("Failed to open file for reading");
    return;
  }
  
  while (file.available())
  {
    String buffer = file.readStringUntil('\n');
    DeserializationError error = deserializeJson(doc, buffer);
    
    if (error)
    {
      Serial.print("Deserialization failed: ");
      Serial.println(error.c_str());
      continue;
    }
    
    // 此处可对doc进行操作,比如修改字段
    String output;
    serializeJson(doc, output); // 将修改后的doc序列化为字符串
    Serial.println(output);
    int httpResponseCode = http.POST(output);
    Serial.println(httpResponseCode);
    doc.clear();
    delay(200);
  }
  
  http.end();
  file.close();
}

额外排查点

  • 确保ESP32-S3的Arduino core版本和其他测试板一致,避免 filesystem 或串口相关的底层差异。
  • 检查SD卡文件内容:可以通过读卡器直接查看all.txt,确认文件中是否真的存在"null"字符(大概率不存在,是代码生成的)。

内容的提问来源于stack exchange,提问作者Blackhoody

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:20:40