用蓝图c++写一个解析json数据的例子
时间: 2023-03-31 12:01:52 浏览: 95
可以使用以下代码解析 JSON 数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cJSON.h>
int main() {
char *json_str = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
cJSON *root = cJSON_Parse(json_str);
if (root == NULL) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
cJSON *name = cJSON_GetObjectItem(root, "name");
cJSON *age = cJSON_GetObjectItem(root, "age");
cJSON *city = cJSON_GetObjectItem(root, "city");
printf("Name: %s\n", name->valuestring);
printf("Age: %d\n", age->valueint);
printf("City: %s\n", city->valuestring);
cJSON_Delete(root);
return ;
}
```
这个例子使用了 cJSON 库来解析 JSON 数据。首先定义一个 JSON 字符串,然后使用 cJSON_Parse 函数将其解析成 cJSON 对象。接着使用 cJSON_GetObjectItem 函数获取对象中的属性值,最后打印出来即可。注意要在最后使用 cJSON_Delete 函数释放内存。