Never too late to learn.

0%

stm32使用cJSON库对JSON格式的打包和解析

介绍 Introduction

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON 无处不在

我们需要两个库,cJSON库和JSON_checker库,cJSON用来JSON格式的封装和解析,JSON_checker库用来做JSON格式的检查,因为如果输入的数据不符合JSON标准,在使用cJSON时会出现死机现象,因此需要对外来数据进行检查,然后才由从JSON做解析。

修改库

需要将内存分配和释放函数修改为自己使用的

1
2
3
static void *(*cJSON_malloc)(size_t sz) = mymalloc;

static void (*cJSON_free)(void *ptr) = myfree;

JSON 封装

1
2
3
4
5
6
7
8
9
10
11
12
13
cJSON *root = NULL;
char *report = NULL;

root = cJSON_CreateObject();

cJSON_AddStringToObject(root, "Key", reportCount);

report = cJSON_PrintUnformatted(root);
cJSON_Delete(root);

...

myfree(report);

JSON 解析

首先需要对解析的数据进行检测,是否为JSON格式,否则直接使用解析函数会导致出错。

JSON 格式检查

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/*
Read input string and check.

if not json string return -1, else return 0.

jc will contain a JSON_checker with a maximum depth of 20.
*/
int json_checker(const char *json_str)
{
JSON_checker jc = new_JSON_checker(20);

int len = strlen(json_str);
int tmp_i = 0;

for (tmp_i = 0; tmp_i < len; tmp_i++)
{
int next_char = json_str[tmp_i];
if (next_char <= 0)
{
break;
}
if (0 == JSON_checker_char(jc, next_char))
{
// fprintf(stderr, "JSON_checker_char: syntax error\n");
return -1;
}
}

if (0 == JSON_checker_done(jc))
{
// fprintf(stderr, "JSON_checker_end: syntax error\n");
return -1;
}

return 0;
}

JSON 格式解析

1
2
3
4
5
6
7
8
9
10
11
12
cJSON *receivedData = cJSON_Parse(mqttSubMsm);

char *rendered =cJSON_Print(receivedData);

printf("Received : %s\r\n", rendered);
value = cJSON_GetObjectItem(receivedData, "key")->valuestring;
printf("key: %s\r\n", key);
printf("value: %s\r\n", value);
...

cJSON_Delete(receivedData);
myfree(rendered);
Coffee? ☕