在Arduino ESP32开发中,处理JSON数据常用的库是 ArduinoJson,它是一个高效、轻量且易用的库,适用于解析和生成JSON格式的数据。以下是关于在ESP32项目中使用JSON库的详细指南:
1. 推荐库:ArduinoJson
- GitHub地址: ArduinoJson
- 特点:
- 支持JSON解析(反序列化)和生成(序列化)。
- 内存占用低,适合嵌入式设备。
- 兼容Arduino IDE和PlatformIO。
- 支持动态和静态内存分配。
2. 安装方法
通过Arduino IDE库管理器安装:
- 打开Arduino IDE。
- 菜单栏选择 工具 > 管理库。
- 搜索
ArduinoJson ,选择最新版本安装。
3. 基本用法示例
解析JSON数据(反序列化)
#include <ArduinoJson.h>
const char* json = "{\"temperature\":25.5,\"humidity\":60}";
void setup() {
Serial.begin(115200);
// 创建JsonDocument对象(动态内存分配)
DynamicJsonDocument doc(1024);
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.print("JSON解析失败: ");
Serial.println(error.c_str());
return;
}
// 提取数据
float temperature = doc["temperature"];
int humidity = doc["humidity"];
Serial.print("温度: ");
Serial.println(temperature);
Serial.print("湿度: ");
Serial.println(humidity);
}
void loop() {}
生成JSON数据(序列化)
#include <ArduinoJson.h>
void setup() {
Serial.begin(115200);
// 创建JsonDocument对象
DynamicJsonDocument doc(1024);
doc["sensor"] = "DHT22";
doc["value"] = 42;
doc["active"] = true;
// 序列化为字符串
String output;
serializeJson(doc, output);
Serial.println(output);
}
void loop() {}
4. 注意事项
内存管理
-
ESP32的堆内存较大(约320KB),但需合理分配 DynamicJsonDocument 的大小。
-
如果启用了ESP32的PSRAM(外部RAM),可在代码中配置ArduinoJson使用PSRAM:
#include <ArduinoJson.h>
struct SpiRamAllocator {
void* allocate(size_t size) { return heap_caps_malloc(size, MALLOC_CAP_SPIRAM); }
void deallocate(void* ptr) { heap_caps_free(ptr); }
};
using SpiRamJsonDocument = BasicJsonDocument<SpiRamAllocator>;
版本兼容性
- ArduinoJson v6.x 是当前主流版本,语法与旧版v5.x不同,建议使用v6.x。
5. 其他JSON库
如果项目对内存要求极高,可考虑以下轻量级库:
- JSON-Variant: 适用于简单键值对。
- SimpleJSON: 代码量少,适合基础解析。
6. 常见问题
Q1: 解析时返回 InvalidInput 错误
- 检查JSON格式是否正确(如引号、逗号)。
- 使用在线工具(如 JSONLint)验证JSON。
Q2: 内存不足导致崩溃
- 增大
DynamicJsonDocument 的大小。
- 减少嵌套层级或简化JSON结构。
7. 进阶应用
-
与HTTP客户端结合(如WiFiClient或HTTPClient):
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
void fetchData() {
HTTPClient http;
http.begin("http://api.example.com/data");
int httpCode = http.GET();
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
DynamicJsonDocument doc(2048);
deserializeJson(doc, payload);
// 处理数据...
}
http.end();
}
-
嵌套JSON处理:
// 示例JSON: {"sensors":[{"name":"temp","value":25}, {"name":"hum","value":60}]}
JsonArray sensors = doc["sensors"];
for (JsonObject sensor : sensors) {
const char* name = sensor["name"];
int value = sensor["value"];
}
通过上述方法,你可以在ESP32项目中高效处理JSON数据。如果需要更复杂的操作,请参考 ArduinoJson官方文档。 |