cJSON代码阅读(2)——cJSON介绍

本文介绍了cJSON库的使用方法,包括解析和生成JSON数据。通过示例代码展示了如何读取和写入JSON对象及数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

cJSON是一个轻巧,携带方便,单文件,简单的并且符合ANSI-C标准的JSON解析器。

下面看看使用它的两个例子(这两个例子也是来源于网上)。

解析json数据:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
#include "cJSON.h"

void parse_json_data()
{
    char text[] = "{\"name\":\"jack\",\"age\":18}";

    cJSON *json , *json_value , *json_timestamp;
    // 解析数据包
    json = cJSON_Parse(text);
    if (!json)
    {
        printf("Error before: [%s]\n",cJSON_GetErrorPtr());
    }
    else
    {
        // 解析值
        json_value = cJSON_GetObjectItem( json , "age");
        if( json_value->type == cJSON_Number )
        {
            // 从valueint中获得结果
            printf("age:%d\r\n",json_value->valueint);
        }
        // 解析时间戳
        json_timestamp = cJSON_GetObjectItem( json , "name");
        if( json_timestamp->type == cJSON_String )
        {
            // valuestring中获得结果
            printf("%s\r\n",json_timestamp->valuestring);
        }
        // 释放内存空间
        cJSON_Delete(json);
    }
}


生成json数据:

void create_json_data()
{
   
    cJSON* pRoot = cJSON_CreateObject();
    cJSON* pArray = cJSON_CreateArray();
    cJSON_AddItemToObject(pRoot, "students_info", pArray);
    char* szOut = cJSON_Print(pRoot);

    cJSON* pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "chenzhongjing");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 28);
    cJSON_AddItemToArray(pArray, pItem);

    pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "fengxuan");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 24);
    cJSON_AddItemToArray(pArray, pItem);

    pItem = cJSON_CreateObject();
    cJSON_AddStringToObject(pItem, "name", "tuhui");
    cJSON_AddStringToObject(pItem, "sex", "male");
    cJSON_AddNumberToObject(pItem, "age", 22);
    cJSON_AddItemToArray(pArray, pItem);

    char* szJSON = cJSON_Print(pRoot);
    cJSON_Delete(pRoot);
    //free(szJSON);

    pRoot = cJSON_Parse(szJSON);
    pArray = cJSON_GetObjectItem(pRoot, "students_info");
    if (NULL == pArray)
    {
        return ;
    }

    int iCount = cJSON_GetArraySize(pArray);
    for (int i = 0; i < iCount; ++i)
    {
        cJSON* pItem = cJSON_GetArrayItem(pArray, i);
        if (NULL == pItem)
        {
            continue;
        }

        string strName = cJSON_GetObjectItem(pItem, "name")->valuestring;
        string strSex = cJSON_GetObjectItem(pItem, "sex")->valuestring;
        int iAge = cJSON_GetObjectItem(pItem, "age")->valueint;
    }

    cJSON_Delete(pRoot);
    free(szJSON);
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值