admin 管理员组

文章数量: 1184232


2024年3月29日发(作者:guava流式细胞仪)

cjson使用方法

CJSON 是 C 语言中用于处理 JSON 数据的库,它可以方便地解析和生成

JSON 数据。下面是 CJSON 库的基本使用方法:

1. 包含头文件

```c

#include

```

2. 创建 JSON 对象

```c

JSON_Object *jsonObject = json_create_object();

```

或者使用 json_create_array() 创建 JSON 数组。

3. 添加元素

```c

json_object_set(jsonObject, "name", JSON_STR, "John"); // 设置

name 节点的值为"John"

json_object_set(jsonObject, "age", JSON_INT, 30); // 设置 age 节

点的值为 30

```

4. 获取元素值

```c

char *name = json_object_get(jsonObject, "name", JSON_STR);

int age = json_object_get(jsonObject, "age", JSON_INT);

```

5. 修改元素值

```c

json_object_set(jsonObject, "age", JSON_INT, 20); // 修改 age 节

点的值为 20

```

6. 删除元素

```c

json_object_del(jsonObject, "age", JSON_INT); // 删除 age 节点

```

7. 遍历 JSON 对象中的所有元素

```c

for (int i = 0; json_object_get(jsonObject, i, type) != JSON_NULL;

i++) {

switch (json_object_get(jsonObject, i, type)) {

case JSON_STR:

printf("Value of field %d is %s

", i, json_object_get(jsonObject, i, JSON_STR));

break;

case JSON_INT:

printf("Value of field %d is %d

", i, json_object_get(jsonObject, i, JSON_INT));

break;

case JSON_ARRAY:

printf("Value of field %d is an array

", i);

json_array_foreach(json_object_get(jsonObject, i, JSON_ARRAY),

node) {

printf("Element %d is %s

", i, json_object_get(node, i, JSON_STR));

}

break;

case JSON_OBJECT:

printf("Value of field %d is an object

", i);

json_object_foreach(json_object_get(jsonObject, i, JSON_OBJECT),

node) {

printf("Field %d is %s

", i, json_object_get(node, i, JSON_STR));

}

break;

}

}

```

8. 释放 JSON 对象内存

```c

json_object_del(jsonObject);

```

以上是 CJSON 库的基本使用方法,它提供了方便的方式来处理 JSON 数据。

使用 CJSON 库可以快速地解析和生成 JSON 数据,并且可以方便地遍历 JSON

对象中的所有元素。


本文标签: 对象 元素 处理 方法 使用