cjson怎么编辑节点
时间: 2023-08-14 10:26:01 浏览: 144
在cjson中,节点的编辑有两种方式:读取和写入。
读取节点:
节点可以通过cJSON_GetObjectItem()函数来读取。它的参数是一个cJSON对象和节点的键名,函数返回一个指向节点的指针。例如,要获取名为"name"的节点,可以使用以下代码:
```
cJSON *root = cJSON_Parse(json_string);
cJSON *name = cJSON_GetObjectItem(root, "name");
```
写入节点:
要写入一个新节点,可以使用cJSON_CreateObject()创建一个新的cJSON对象,并使用cJSON_AddItemToObject()将它添加到父节点中。例如,要添加一个新节点"name",并将其设置为"John",可以使用以下代码:
```
cJSON *root = cJSON_CreateObject();
cJSON_AddItemToObject(root, "name", cJSON_CreateString("John"));
```
要编辑一个已存在的节点,在获取节点指针后,可以使用不同的cJSON_Set函数来设置节点的值。例如,要将名为"name"的节点的值更改为"Mike",可以使用以下代码:
```
cJSON *root = cJSON_Parse(json_string);
cJSON *name = cJSON_GetObjectItem(root, "name");
cJSON_SetValuestring(name, "Mike");
```
需要注意的是,一旦创建了cJSON对象,就需要使用cJSON_Delete()函数来释放内存。
阅读全文
相关推荐


















