溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

C語言怎么用cJSON解析JSON格式

發(fā)布時(shí)間:2023-04-21 15:16:01 來源:億速云 閱讀:119 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“C語言怎么用cJSON解析JSON格式”,在日常操作中,相信很多人在C語言怎么用cJSON解析JSON格式問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”C語言怎么用cJSON解析JSON格式”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!

一、JSON格式

語法:鍵 / 值

1、以 { 開始,以 } 結(jié)束,允許嵌套使用

2、每個(gè)鍵和值成對(duì)出現(xiàn),并使用:分隔。如"age"=23

3、鍵值對(duì)之間用 ,分隔

值的多種類型:

字符串:用 " "

{
    "name":"code",
    "gender":"male"
}

數(shù)字:整數(shù)或浮點(diǎn)數(shù)都直接表示

{
    "key1":10,
    "key2":20.0
}

數(shù)組:用[ ]

 {
     "key1" : [0, 1],
     "key2" : [2, 3]
 }

布爾值:fault、true

二、cJSON下載

git clone https://gitee.com/peng-jiaweibabe/c-json.git

cJSON的.c和.h文件,使用的時(shí)候,只需要將這兩個(gè)文件復(fù)制到工程目錄,然后包含頭文件cJSON.h即可。即#include "cJSON.h"

如若出現(xiàn)該情況,鏈接math庫(kù)即可 

C語言怎么用cJSON解析JSON格式

三、cJSON常用函數(shù)接口

1.cJSON_Parse

CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)
 
函數(shù)功能:將一個(gè)JSON字符串,按照cJSON結(jié)構(gòu)體的結(jié)構(gòu)序列化整個(gè)數(shù)據(jù)包,并在堆中開辟一塊內(nèi)存存儲(chǔ)cJSON結(jié)構(gòu)體
 
返回值:成功返回一個(gè)指向內(nèi)存塊中的cJSON的指針,失敗返回NULL

2.cJSON_Print

CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)    //按JSON格式打印
    
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)    //不按JSON格式打印
 
函數(shù)功能:將整條鏈表中存放的JSON信息輸出到一個(gè)字符串中,使用時(shí)只需用一個(gè)字符串指針(char *)接收該函數(shù)返回的指針地址即可。
 
返回值:成功返回一個(gè)char*指針并指向位于堆中JSON字符串,失敗返回NULL

3.cJSON_Delete

CJSON_PUBLIC(void) cJSON_Delete(cJSON *c)
 
函數(shù)功能:釋放位于堆中cJSON結(jié)構(gòu)體內(nèi)存
 
返回值:無

4.cJSON_GetObjectItem

(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
 
函數(shù)功能:根據(jù)鍵值對(duì)的名稱從鏈表中取出對(duì)應(yīng)的值,返回該鍵值對(duì)(鏈表節(jié)點(diǎn))的地址
 
返回值:成功返回一個(gè)指向內(nèi)存塊中的cJSON的指針,失敗返回NULL

5.cJSON_GetObjectItem(數(shù)組相關(guān))

CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)
(int) cJSON_GetArraySize(const cJSON *array)
(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index)

6.創(chuàng)建對(duì)象函數(shù)接口

/* raw json */
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
/* These calls create a cJSON item of the appropriate type. */
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
/* These utilities create an Array of count items. */
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char **strings, int count);

7.添加cJSON對(duì)象到鏈表

CJSON_PUBLIC(void) cJSON_AddItemToArray(cJSON *array, cJSON *item);
CJSON_PUBLIC(void) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);

8.從現(xiàn)有的cJSON鏈表中刪除一個(gè)對(duì)象

CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);

四、cJSON解析JSON案例

1.一層鍵值

/*********************************************************************************
 *      Copyright:  (C) 2022 Nbiot<lingyun@gail.com>
 *                  All rights reserved.
 *
 *       Filename:  test_cjson.c
 *    Description:  This file test_cjson.c
 *
 *        Version:  1.0.0(30/05/22)
 *         Author:  Nbiot <lingyun@gail.com>
 *      ChangeLog:  1, Release initial version on "30/05/22 20:25:49"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include "cJSON.h"
 
int main (int argc, char **argv)
{
        char json_buf[] = "{\"type\":\"text\",\"number\":1111,\"sms\":\"nihao\"}";
 
        cJSON *json = NULL;
        cJSON *json_type = NULL;
        cJSON *json_num = NULL;
        cJSON *json_sms = NULL;
 
        printf("json格式化前:\n");
        printf("%s\n\n", json_buf);
 
        json = cJSON_Parse(json_buf);   //json格式序列化
 
        if (NULL == json)
        {
                printf("cJSON_Parse error:%s\n", cJSON_GetErrorPtr());
        }
 
        printf("json格式化后:\n");
        printf("%s\n\n",cJSON_Print(json));
 
        /* 獲取相應(yīng)key的value */
        json_type = cJSON_GetObjectItem(json, "type");
        json_num = cJSON_GetObjectItem(json, "number");
        json_sms = cJSON_GetObjectItem(json, "sms");
 
        printf("type:%s\n", json_type->valuestring);
        printf("number:%d\n", json_num->valueint);
        printf("sms:%s\n", json_sms->valuestring);
 
        cJSON_Delete(json);             //釋放cjson結(jié)構(gòu)體內(nèi)存
 
        return 0;
}

結(jié)果:

C語言怎么用cJSON解析JSON格式

2.多層鍵值(兩次為例)

/*********************************************************************************
 *      Copyright:  (C) 2022 Nbiot<lingyun@gail.com>
 *                  All rights reserved.
 *
 *       Filename:  test_cjson1.c
 *    Description:  This file test_cjson1.c
 *
 *        Version:  1.0.0(30/05/22)
 *         Author:  Nbiot <lingyun@gail.com>
 *      ChangeLog:  1, Release initial version on "30/05/22 23:36:09"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include "cJSON.h"
 
int main (int argc, char **argv)
{
        char json_buf[] =  "{\"type\":\"text\",\"number\":{\"phone_number\":\"17687499242\"},\"sms\":\"nihao\"}";
 
        cJSON *json = NULL;
        cJSON *json_phone_number = NULL;
 
        printf("json格式化前:\n");
        printf("%s\n\n", json_buf);
 
        json = cJSON_Parse(json_buf);   //json格式序列化
 
        if (NULL == json)
        {
                printf("cJSON_Parse error:%s\n", cJSON_GetErrorPtr());
        }
 
        printf("json格式化后:\n");
        printf("%s\n\n",cJSON_Print(json));
 
        /* 獲取相應(yīng)key的value */
        json_phone_number = cJSON_GetObjectItem(json, "number");    //首先獲取第一次鍵值
 
        json_phone_number = cJSON_GetObjectItem(json_phone_number, "phone_number");    //獲取第二層
 
        printf("phone_number:%s\n", json_phone_number->valuestring);
 
        cJSON_Delete(json);             //釋放cjson結(jié)構(gòu)體內(nèi)存
 
        return 0;
}

結(jié)果:

C語言怎么用cJSON解析JSON格式

3.json數(shù)組解析

/*********************************************************************************
 *      Copyright:  (C) 2022 Nbiot<lingyun@gail.com>
 *                  All rights reserved.
 *
 *       Filename:  test_cjson3.c
 *    Description:  This file test_cjson3.c
 *
 *        Version:  1.0.0(31/05/22)
 *         Author:  Nbiot <lingyun@gail.com>
 *      ChangeLog:  1, Release initial version on "31/05/22 00:14:13"
 *
 ********************************************************************************/
#include <stdio.h>
#include <string.h>
#include "cJSON.h"
 
int main (int argc, char **argv)
{
        char json_buf[] = "{\"type\":\"text\",\"number\":1111,\"sms\":\"nihao\",\"array\":[1,2,3]}";
 
        cJSON *json = NULL;
        cJSON *json_array = NULL;
        int array_size=0;
        cJSON *json_array_value = NULL;
 
        printf("json格式化前:\n");
        printf("%s\n\n", json_buf);
 
        json = cJSON_Parse(json_buf);   //json格式序列化
 
        if (NULL == json)
        {
                printf("cJSON_Parse error:%s\n", cJSON_GetErrorPtr());
        }
 
        printf("json格式化后:\n");
        printf("%s\n\n",cJSON_Print(json));
 
        json_array = cJSON_GetObjectItem(json, "array");    
        array_size = cJSON_GetArraySize(json_array);    //獲取數(shù)組大小
 
        printf("array_size=%d\n",array_size);
 
        for(int i=0; i<array_size; i++)
        {
                json_array_value = cJSON_GetArrayItem(json_array, i);
                printf("array[%d]=%d\n", i,json_array_value->valueint);
        }
 
        cJSON_Delete(json);             //釋放cjson結(jié)構(gòu)體內(nèi)存
 
        return 0;
}

 結(jié)果:

C語言怎么用cJSON解析JSON格式

五、JSON添加數(shù)據(jù) (與鏈表類似)

三層鍵值

/*********************************************************************************
 *      Copyright:  (C) 2022 Nbiot<lingyun@gail.com>
 *                  All rights reserved.
 *
 *       Filename:  test_cjson2.c
 *    Description:  This file test_cjson2.c
 *
 *        Version:  1.0.0(30/05/22)
 *         Author:  Nbiot <lingyun@gail.com>
 *      ChangeLog:  1, Release initial version on "30/05/22 20:46:57"
 *
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"
 
int main(int argc, char **argv)
{
        char *json_ptr = NULL;
        cJSON * root   =  cJSON_CreateObject();
        cJSON * son    =  cJSON_CreateObject();
        cJSON * next   =  cJSON_CreateObject();
 
        cJSON_AddItemToObject(root, "gender", cJSON_CreateString("male"));
        cJSON_AddItemToObject(root, "student", son); //第一層嵌套鍵值
        cJSON_AddItemToObject(son,      "name", cJSON_CreateString("xiaochen"));//第二層嵌套鍵值
        cJSON_AddItemToObject(son,      "school", next); //第二層嵌套鍵值
        cJSON_AddItemToObject(next, "name", cJSON_CreateString("high school"));//第三層嵌套鍵值
 
        json_ptr = cJSON_Print(root);
        printf("JSON:\n", json_ptr);
        printf("%s\n", json_ptr);
 
        free(json_ptr);
 
        cJSON_Delete(root);
 
        return 0;
}

結(jié)果:

C語言怎么用cJSON解析JSON格式

到此,關(guān)于“C語言怎么用cJSON解析JSON格式”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI