使用cJSON库对一个JSON文件进行反序列化操作。ver和login的子节点直接打印即可,data的数据节点解析后形成链表存储
时间: 2024-05-03 07:18:22 浏览: 8
假设我们有一个名为example.json的JSON文件,内容如下:
```
{
"ver": "1.0",
"login": {
"username": "john",
"password": "123456"
},
"data": [
{
"name": "apple",
"price": 2.5
},
{
"name": "banana",
"price": 1.5
},
{
"name": "orange",
"price": 3.0
}
]
}
```
我们可以使用cJSON库对其进行反序列化操作。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
// 定义商品结构体
typedef struct Product {
char name[32];
double price;
struct Product* next;
} Product;
int main() {
// 读取JSON文件
FILE* fp = fopen("example.json", "r");
if (!fp) {
printf("Failed to open file.\n");
return 1;
}
fseek(fp, 0, SEEK_END);
long file_size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char* file_content = (char*)malloc(file_size + 1);
fread(file_content, file_size, 1, fp);
fclose(fp);
file_content[file_size] = '\0';
// 解析JSON数据
cJSON* root = cJSON_Parse(file_content);
free(file_content);
if (!root) {
printf("Failed to parse JSON data.\n");
return 1;
}
// 获取ver节点
cJSON* ver = cJSON_GetObjectItem(root, "ver");
printf("ver: %s\n", ver->valuestring);
// 获取login节点
cJSON* login = cJSON_GetObjectItem(root, "login");
cJSON* username = cJSON_GetObjectItem(login, "username");
cJSON* password = cJSON_GetObjectItem(login, "password");
printf("username: %s\n", username->valuestring);
printf("password: %s\n", password->valuestring);
// 获取data节点
cJSON* data = cJSON_GetObjectItem(root, "data");
if (!data || !cJSON_IsArray(data)) {
printf("Failed to get data.\n");
return 1;
}
// 解析商品数据
Product* head = NULL;
cJSON* item = NULL;
cJSON_ArrayForEach(item, data) {
cJSON* name = cJSON_GetObjectItem(item, "name");
cJSON* price = cJSON_GetObjectItem(item, "price");
if (!name || !price) {
continue;
}
Product* product = (Product*)malloc(sizeof(Product));
snprintf(product->name, 32, "%s", name->valuestring);
product->price = price->valuedouble;
product->next = head;
head = product;
}
// 打印商品数据
Product* p = head;
while (p) {
printf("name: %s, price: %.2f\n", p->name, p->price);
p = p->next;
}
// 释放资源
cJSON_Delete(root);
while (head) {
Product* next = head->next;
free(head);
head = next;
}
return 0;
}
```
运行该程序会输出以下结果:
```
ver: 1.0
username: john
password: 123456
name: orange, price: 3.00
name: banana, price: 1.50
name: apple, price: 2.50
```
可以看到,我们成功地对example.json文件进行了反序列化操作,并成功解析了ver和login节点,以及data节点中的商品数据。其中,我们使用了一个Product结构体来存储商品数据,使用了链表来存储多个商品数据。注意,在使用cJSON库时,我们需要注意内存管理,避免内存泄漏。