cJson实现解析数组
时间: 2024-02-25 17:59:35 浏览: 28
cJson可以很方便地解析JSON数组,下面是一个例子:
假设有以下JSON字符串:
```json
{
"name": "John",
"age": 30,
"pets": ["dog", "cat", "fish"]
}
```
我们可以使用cJson解析该字符串,获取pets数组中的元素:
```c
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
int main() {
char* json_str = "{\"name\":\"John\",\"age\":30,\"pets\":[\"dog\",\"cat\",\"fish\"]}";
cJSON* root = cJSON_Parse(json_str);
if (!root) {
printf("Error before: [%s]\n", cJSON_GetErrorPtr());
return 1;
}
cJSON* pets = cJSON_GetObjectItemCaseSensitive(root, "pets");
if (!pets) {
printf("Failed to get pets array.\n");
cJSON_Delete(root);
return 1;
}
if (!cJSON_IsArray(pets)) {
printf("Pets is not an array.\n");
cJSON_Delete(root);
return 1;
}
int pets_size = cJSON_GetArraySize(pets);
printf("Pets array size: %d\n", pets_size);
for (int i = 0; i < pets_size; ++i) {
cJSON* pet = cJSON_GetArrayItem(pets, i);
if (!cJSON_IsString(pet)) {
printf("Pet at %d is not a string.\n", i);
cJSON_Delete(root);
return 1;
}
printf("Pet %d: %s\n", i, pet->valuestring);
}
cJSON_Delete(root);
return 0;
}
```
输出:
```
Pets array size: 3
Pet 0: dog
Pet 1: cat
Pet 2: fish
```
在上面的代码中,我们首先解析JSON字符串,然后获取pets数组的指针。接着,我们判断pets是否是一个数组,并获取它的大小。最后,我们遍历数组中的元素,输出它们的值。
注意,我们必须检查每个元素的类型,以确保它是一个字符串。否则,解析过程可能会失败或产生意外的结果。