windows c++ cjson 封装json示例
时间: 2024-01-05 14:19:35 浏览: 46
以下是使用CJSON封装JSON的示例:
1. 创建一个JSON数组并向其中添加一个JSON对象
```c
cJSON *array = cJSON_CreateArray();
cJSON *item = cJSON_CreateObject();
cJSON_AddItemToArray(array, item);
```
2. 向JSON对象中添加一个字符串类型的键值对
```c
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "friend-list");
```
相关问题
cjson读取json文件
CJSON是一个轻量级的C语言JSON解析库,它简单易用,适合处理小型到中型的JSON数据。如果你想在C语言项目中读取JSON文件,CJSON提供了一系列函数来帮助你完成这个任务。以下是如何使用CJSON读取JSON文件的基本步骤:
1. 首先,确保已经包含了CJSON的头文件`cjson.h`。
2. 使用`cjson_load_file`函数打开并加载JSON文件,例如:
```c
#include <cjson/cjson.h>
FILE *file = fopen("example.json", "r");
cJSON *root = cjson_load_file(file, NULL);
if (!root) {
// 处理错误,如文件读取失败或JSON解析失败
}
```
这里的`example.json`是你要读取的JSON文件名,如果文件存在且格式正确,`cjson_load_file`会返回一个指向解析后的`cJSON`结构的指针。
3. 你可以通过遍历`cJSON`树来访问和操作数据。例如,获取键值对:
```c
const char *key = cJSON_GetObjectItem(key_path, root)->name;
cJSON *value = cJSON_GetObjectItem(key_path, root);
```
这里`key_path`是一个字符串,表示在JSON对象中的路径(例如,`"data.field"`)。
4. 解析完成后,别忘了关闭文件和释放资源:
```c
fclose(file);
cjson_free(root);
```
cjson解析json
cjson 是一个非常快速的 C 语言 JSON 解析库,可以轻松地解析 JSON 字符串并将其转换为 C 语言中的数据类型,例如 Lua 中的 table 类型。以下是使用 cjson 解析 JSON 的基本步骤:
1. 引入 cjson 库:
```
#include "cJSON.h"
```
2. 定义一个 cJSON 对象:
```
cJSON *root = NULL;
```
3. 调用 cjson 的解析函数将 JSON 字符串转换为 cJSON 对象:
```
root = cJSON_Parse(json_string);
```
4. 使用 cJSON 对象中的函数获取 JSON 中的数据:
```
cJSON *item = cJSON_GetObjectItemCaseSensitive(root, "key");
```
其中,"key" 为要获取的 JSON 属性名。
5. 将 cJSON 对象销毁:
```
cJSON_Delete(root);
```
完整的示例代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
char *json_string = "{\"name\":\"Alice\",\"age\":18,\"gender\":\"female\"}";
cJSON *root = NULL;
root = cJSON_Parse(json_string);
cJSON *name = cJSON_GetObjectItemCaseSensitive(root, "name");
cJSON *age = cJSON_GetObjectItemCaseSensitive(root, "age");
cJSON *gender = cJSON_GetObjectItemCaseSensitive(root, "gender");
printf("name: %s\n", name->valuestring);
printf("age: %d\n", age->valueint);
printf("gender: %s\n", gender->valuestring);
cJSON_Delete(root);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)