json解析 C++
时间: 2023-11-14 09:06:57 浏览: 42
在 C 语言中,可以使用第三方库 cJSON 进行 JSON 解析。cJSON 是一个轻量级的、适用于嵌入式设备的 JSON 解析器,可以方便地解析 JSON 字符串并以 C 语言的数据结构进行访问。
使用 cJSON 解析 JSON 的一般步骤如下:
1. 调用 cJSON_Parse 函数解析 JSON 字符串,返回 cJSON 结构体指针。
2. 使用 cJSON_GetObjectItem 函数获取 cJSON 结构体中的子项。
3. 根据子项的类型使用对应的 cJSON_GetXxx 函数获取子项的值。
4. 使用 cJSON_Delete 函数释放 cJSON 结构体。
下面是一个简单的使用 cJSON 解析 JSON 字符串的例子:
```c
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main()
{
char *json_str = "{\"name\":\"Tom\",\"age\":20,\"scores\":[80,90,85]}";
cJSON *root = cJSON_Parse(json_str);
if (root == NULL) {
printf("JSON parse error!\n");
return -1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
if (name != NULL) {
printf("name: %s\n", name->valuestring);
}
cJSON *age = cJSON_GetObjectItem(root, "age");
if (age != NULL) {
printf("age: %d\n", age->valueint);
}
cJSON *scores = cJSON_GetObjectItem(root, "scores");
if (scores != NULL && cJSON_IsArray(scores)) {
int i;
for (i = 0; i < cJSON_GetArraySize(scores); i++) {
cJSON *score = cJSON_GetArrayItem(scores, i);
if (score != NULL) {
printf("score[%d]: %d\n", i, score->valueint);
}
}
}
cJSON_Delete(root);
return 0;
}
```
输出结果为:
```
name: Tom
age: 20
score[0]: 80
score[1]: 90
score[2]: 85
```