关于下载RT-Thread和移植Fatfs文件系统可以参考博客:
STM32F429IGT6的RT-Thread移植Fatfs文件系统
一、下载 和配置cJSON开源文件
1、下载文件
通过github网站:GitHub - DaveGamble/cJSON: Ultralightweight JSON parser in ANSI C
在项目\rt-thread-master\bsp\stm32\stm32f429-fire-challenger\applications创建cJSON文件夹用于保存cJSON.c和cJSON.h。
2、配置文件
在项目中创建如下目录并导入相关文件。
二、函数解析和调用
1、函数例子
下列函数创建出的cjson内容为,大家可以自己对应着改,就不过多解释了:
{
"SN": "01001",
"StationNumber": "01",
"Data": {
"LargeData": [{
"TestID": "01",
"PulseInterval": "500ms",
}],
"SmallData": [{
"TestID": "01",
"PulseInterval": "500ms",
}],
"FullData": {
"StartTime": "202408131522",
"EndTime": "202408131526",
}
},
"IsDataComplete": true
}
char* create_json_data(void)
{
// Create the root JSON object
cJSON *root = cJSON_CreateObject();
// Add "SN" and "StationNumber"
cJSON_AddStringToObject(root, "SN", "01001");
cJSON_AddStringToObject(root, "StationNumber", "01");
// Create the "Data" object
cJSON *data = cJSON_CreateObject();
cJSON_AddItemToObject(root, "Data", data);
// Create the "LargeData" array
cJSON *largeData = cJSON_CreateArray();
cJSON_AddItemToObject(data, "LargeRData", largeData);
// Create and add an object to "LargeData" array
cJSON *largeEntry = cJSON_CreateObject();
cJSON_AddItemToArray(largeData, largeEntry);
cJSON_AddStringToObject(largeEntry, "TestID", "01");
cJSON_AddStringToObject(largeEntry, "PulseInterval", "500ms");
// Create the "SmallRainfallData" array
cJSON *smallData = cJSON_CreateArray();
cJSON_AddItemToObject(data, "SmallData", smallData);
// Create and add an object to "SmallData" array
cJSON *smallRainfallEntry = cJSON_CreateObject();
cJSON_AddItemToArray(smallData, smallEntry);
cJSON_AddStringToObject(smallEntry, "TestID", "01");
cJSON_AddStringToObject(smallEntry, "PulseInterval", "500ms");
// Create the "ProcessData" object
cJSON *fullProcessData = cJSON_CreateObject();
cJSON_AddItemToObject(data, "ProcessData", ProcessData);
cJSON_AddStringToObject(ProcessData, "StartTime", "202408131522");
cJSON_AddStringToObject(ProcessData, "EndTime", "202408131526");
// Add "IsDataComplete"
cJSON_AddBoolToObject(root, "IsDataComplete", 1);
// Convert JSON object to string
char *jsonString = cJSON_Print(root);
// Free the cJSON object
cJSON_Delete(root);
return jsonString;
}
2、函数调用并转字符串
char *json_data = create_json_data();
size_t json_length = strlen(json_data) + 1; // 计算 JSON 数据长度,包含 '\0' 结束符
rt_kprintf("length:%d,%s\r\n", json_length,json_data);
uint8_t WriteBuffer[700]; // 创建 uint8_t 数组
memcpy(WriteBuffer, json_data, strlen(json_data) + 1); // 复制数据到 uint8_t 数组
// 使用完毕后释放内存
free(json_data);