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

ESP32中HTTP请求返回的JSON字符串无法按换行符分割问题求助

字符串分割问题:HTTP请求获取的带转义换行符的字符串无法分割

问题背景

手动赋值包含\n换行符的字符串时,用strtok_r按\n分割能正常工作;但从HTTP请求返回的JSON中提取的表面格式完全一致的字符串,却无法被正确分割,直接输出完整内容。

手动赋值测试(正常运行)

代码:

String text = "First news\nSecond news 2\nAnother news 3\nAnother 4 news.\nLast news 5";

const char* sz = text.c_str(); // 获取字符串指针                        
char *p = (char*)sz; // strtok_r需要非const指针
char *sentence;

while ((sentence = strtok_r(p, "\n", &p)) != NULL) { // 以\n为分隔符
    Serial.println(sentence);
    delay(4);
}

串口输出:

First news
Second news 2
Another news 3
Another 4 news
Last news 5

HTTP请求获取后的分割代码(异常)

从JSON中提取的news字段内容显示为"First news\nSecond news 2\nAnother news 3\nAnother 4 news.\nLast news 5",但分割代码无法生效:

const char* news = doc[0]["news"];
String newsFromServer = String(news); 
const char* sz = newsFromServer.c_str();
char *p = (char*)sz; 
char *sentence;
while ((sentence = strtok_r(p, "\n", &p)) != NULL) { // 以\n为分隔符
    Serial.println(sentence);
    delay(4);
}

实际串口输出(首次循环):

First news\nSecond news 2\nAnother news 3\nAnother 4 news.\nLast news 5

预期首次输出:

First news

已尝试的无效方法

char *sz = strdup(newsFromServer);
char *p = strdup(sz); 

问题原因

JSON返回的字符串中,\n是转义序列——实际存储的是两个独立字符:'\\'(反斜杠)和'n',而非单个换行符'\n'。strtok_r找的是单个换行符,自然无法匹配到分隔位置。

解决方案

先将字符串中的转义序列\\n替换为真正的换行符\n,再执行分割操作:

const char* news = doc[0]["news"];
String newsFromServer = String(news);

// 替换转义的\\n为真实换行符\n
int pos = 0;
while ((pos = newsFromServer.indexOf("\\n", pos)) != -1) {
    newsFromServer.replace(pos, 2, "\n");
    pos += 1; // 跳过已替换的换行符,避免重复匹配
}

// 创建可修改的字符串副本(strtok_r会修改原字符串)
char* sz = strdup(newsFromServer.c_str());
char* p = sz;
char* sentence;

while ((sentence = strtok_r(p, "\n", &p)) != NULL) {
    Serial.println(sentence);
    delay(4);
}

free(sz); // 释放strdup分配的内存,避免内存泄漏

关键注意事项

  • 不能直接使用String::c_str()返回的只读指针强制转换为可写指针,这会触发未定义行为,必须用strdup创建可修改的副本
  • 替换操作中要匹配"\\n"(C++字符串中反斜杠需要转义),替换为单个"\n"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 02:05:35