项目场景:
在我的毕业设计里,有这样一个场景,我要从上位机下发json数据,在STM32上解包。
问题描述
由于之前的项目使用的是jasson库,这次想换成cJSON库
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
const char* json_data = "[{\"name\": \"\\u82f9\\u679c\", \"net_weight\": 500, \"quantity\": 2, \"shelf\": 6}, {\"name\": \"\\u96ea\\u68a8\", \"net_weight\": 0, \"quantity\": 1, \"shelf\": 6}, {\"name\": \"\\u6a58\\u5b50\", \"net_weight\": 0, \"quantity\": 7, \"shelf\": 7}, {\"name\": \"\\u69b4\\u83b2\", \"net_weight\": 0, \"quantity\": 3, \"shelf\": 8}, {\"name\": \"\\u624b\\u673a\", \"net_weight\": 0, \"quantity\": 4, \"shelf\": 9}, {\"name\": \"\\u5e73\\u677f\\u7535\\u8111\", \"net_weight\": 0, \"quantity\": 9, \"shelf\": 10}, {\"name\": \"\\u7b14\\u8bb0\\u672c\\u7535\\u8111\", \"net_weight\": 0, \"quantity\": 10, \"shelf\": 11}, {\"name\": \"\\u65fa\\u65fa\\u96ea\\u997c\", \"net_weight\": 0, \"quantity\": 9, \"shelf\": 9}]";
cJSON* json = cJSON_Parse(json_data);
if (json == NULL) {
printf("Error parsing JSON: %s\n", cJSON_GetErrorPtr());
return 1;
}
cJSON* item = json->child;
// Define arrays to store data
const int array_size = cJSON_GetArraySize(json);
char* name_array[10] = {0};
unsigned int net_weight_array[10] = { 0 };
unsigned int quantity_array[10] = { 0 };
unsigned int shelf_array[10] = { 0 };
int index = 0;
// Iterate over each object in the array
while (item != NULL && index < 10) {
cJSON* name = cJSON_GetObjectItem(item, "name");
cJSON* net_weight = cJSON_GetObjectItem(item, "net_weight");
cJSON* quantity = cJSON_GetObjectItem(item, "quantity");
cJSON* shelf = cJSON_GetObjectItem(item, "shelf");
// Store data in arrays
name_array[index] = name->valuestring;
net_weight_array[index] = net_weight->valueint;
quantity_array[index] = quantity->valueint;
shelf_array[index] = shelf->valueint;
index++;
item = item->next;
}
// Print data stored in arrays
printf("Name Array:\n");
for (int i = 0; i < array_size; i++) {
printf("Name:%s Net Weight:%d Quantity:%d Shelf:%d\n", name_array[i], net_weight_array[i], quantity_array[i], shelf_array[i]);
}
// Free JSON structure
cJSON_Delete(json);
return 0;
}
原因分析:
在运行的时候发现,这段代码在PC端运行是没有任何问题的,但是在STM32端总是报:Error parsing JSON
本想着cJSON不行,我就换回Jasson库,但发现两个都不行,就十分奇怪。代码也是没有错误的,就总是解析不出来。
解决方案:
后来在网上搜索发现了是cJSON在解析数据的时候会不断申请内存,是内存爆了,才会一直这样,所以我们得把堆该大一点,就可以了。PS:下图是已经修改过的。