要解析JSON文件,可以使用json-c库,具体步骤如下:
1. 引入json-c库的头文件
```c
#include <json-c/json.h>
```
2. 读取JSON文件内容
```c
FILE *fp = fopen("filename.json", "r");
if (fp == NULL)
{
printf("Failed to open file\n");
return -1;
}
char buffer[1024];
fread(buffer, 1, 1024, fp);
fclose(fp);
```
3. 解析JSON文件内容
```c
struct json_object *json_obj = json_tokener_parse(buffer);
```
4. 获取JSON对象的值
```c
// 获取字符串类型的值
const char *str_value;
json_object_object_get_ex(json_obj, "key", &str_value);
printf("%s\n", str_value);
// 获取整数类型的值
int int_value;
json_object_object_get_ex(json_obj, "key", &int_value);
printf("%d\n", int_value);
// 获取数组类型的值
struct json_object *arr_obj;
json_object_object_get_ex(json_obj, "key", &arr_obj);
int arr_len = json_object_array_length(arr_obj);
for (int i = 0; i < arr_len; i++)
{
struct json_object *item = json_object_array_get_idx(arr_obj, i);
// 处理数组项
}
```
完整的示例代码如下:
```c
#include <stdio.h>
#include <json-c/json.h>
int main()
{
FILE *fp = fopen("example.json", "r");
if (fp == NULL)
{
printf("Failed to open file\n");
return -1;
}
char buffer[1024];
fread(buffer, 1, 1024, fp);
fclose(fp);
struct json_object *json_obj = json_tokener_parse(buffer);
const char *str_value;
json_object_object_get_ex(json_obj, "name", &str_value);
printf("name: %s\n", str_value);
int age_value;
json_object_object_get_ex(json_obj, "age", &age_value);
printf("age: %d\n", age_value);
struct json_object *hobby_arr_obj;
json_object_object_get_ex(json_obj, "hobbies", &hobby_arr_obj);
int hobby_arr_len = json_object_array_length(hobby_arr_obj);
printf("hobbies:\n");
for (int i = 0; i < hobby_arr_len; i++)
{
struct json_object *item = json_object_array_get_idx(hobby_arr_obj, i);
printf("- %s\n", json_object_get_string(item));
}
json_object_put(json_obj);
return 0;
}
```
需要注意的是,使用完json对象后,需要调用`json_object_put`函数释放内存。