Loading

cJSON:解析JSON

解析数组

将JSON数组解析并存储到自定义的结构体组合的单链表中,打印单链表中所有的结点数据。

例如:

[
  {
    "name": "Zhao",
    "age": 18
  },
  {
    "name": "Qian",
    "age": 19
  },
  {
    "name": "Sun",
    "age": 20
  }
]

需要用一个结构体保存 nameage 的值,单链表保存多个结构体内容。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "cJSON.h"

// 结点数据部分声明
typedef struct node_data_t
{
    char name[20];
    int age;
}node_data_t;

// 结点和链表声明
typedef struct node_t
{
    node_data_t data;
    struct node_t *next;
} node_t, *link_list_t;

// 链表初始化,malloc一个头节点
int list_init(link_list_t *L)
{
    *L = (node_t *)malloc(sizeof(node_t));
    if (NULL == (*L))
        return 1;
    memset(*L, 0, sizeof(node_t));
    (*L)->next = NULL;

    return 0;
}

// 链表释放,释放全部结点内容,包括头结点在内
int list_free(link_list_t *L)
{
    node_t *tmp = NULL;
    while (*L)
    {
        tmp = *L;
        *L = (*L)->next;
        free(tmp);
    }

    return 0;
}

// 链表尾部插入一个结点
int list_insert(link_list_t L, node_data_t data)
{
    node_t *last = L;
    if (L == NULL)
        return 1;
    // 尾插法
    while (last->next != NULL)
        last = last->next;
    node_t *curr = (node_t *)malloc(sizeof(node_t));
    if (NULL == curr)
        return 2;
    memset(curr, 0, sizeof(node_t));
    curr->data = data;
    curr->next = NULL;
    last->next = curr;

    return 0;
}

// 打印链表的结点数据
int list_print(link_list_t L)
{
    node_t *curr = NULL;
    printf("name      age       \n");
    printf("====================\n");
    for (curr = L->next; curr != NULL; curr = curr->next)
    {
        printf("%-10s%-10d\n", curr->data.name, curr->data.age);
    }

    return 0;
}

// 解析JSON 数组,将数据保存到链表
int json_array_string_parse(link_list_t L, const char *json_str)
{
    // 解析 JSON 字符串
    cJSON *root = cJSON_Parse(json_str);
    if (root == NULL)
    {
        fprintf(stderr, "Error parsing JSON\n");
        return 1;
    }

    // 遍历 JSON 数组
    cJSON *item = root->child; //将item指向第一个object,即 {}
    while (item != NULL)
    {
        // 获取 name 和 age 的值
        cJSON *iname = NULL;
        cJSON *iage = NULL; 
        iname = cJSON_GetObjectItem(item, "name");
        iage = cJSON_GetObjectItem(item, "age");

        // 插入新节点到链表
        node_data_t data;
        memset(&data, 0, sizeof(node_data_t));

        strcpy(data.name, iname->valuestring);
        data.age = iage->valueint;

        list_insert(L, data);

        // 移动到下一个元素
        item = item->next;
    }
    cJSON_Delete(root);

    return 0;
}

int main()
{
    link_list_t list;
    list_init(&list);

    const char *jsonString = "[{\"name\": \"Zhao\", \"age\": 18 }, "
                              "{\"name\": \"Qian\", \"age\": 19}, "
                              "{\"name\": \"Sun\", \"age\": 20}]";

    json_array_string_parse(list, jsonString);

    list_print(list);

    list_free(&list);

    return 0;
}


结果:

posted @ 2024-07-03 20:25  eiSouthBoy  阅读(189)  评论(0)    收藏  举报