C語言利用cJSON解析JSON格式全過程
前言
在做的項(xiàng)目需要發(fā)JSON格式的消息并解析,因此學(xué)習(xí)了利用cJSON解析JSON格式,該格式易于人閱讀和編寫。同時(shí)也易于機(jī)器解析和生成。
一、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下載
gitee倉庫:https://gitee.com/peng-jiaweibabe/c-json
git clone https://gitee.com/peng-jiaweibabe/c-json.git
cJSON的.c和.h文件,使用的時(shí)候,只需要將這兩個(gè)文件復(fù)制到工程目錄,然后包含頭文件cJSON.h即可。即#include "cJSON.h"
如若出現(xiàn)該情況,鏈接math庫即可


三、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é)果:

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é)果:

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é)果:

五、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é)果:

總結(jié)
到此這篇關(guān)于C語言利用cJSON解析JSON格式的文章就介紹到這了,更多相關(guān)cJSON解析JSON格式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C++深入講解namespace與string關(guān)鍵字的使用
namespace命名空間或者叫名字空間,傳統(tǒng)的c++只有一個(gè)全局的namespace,namespace引入了復(fù)雜性。namespace允許像類,對(duì)象,函數(shù)聚集在一個(gè)名字下。本質(zhì)上講namespace是對(duì)全局作用域的細(xì)分2022-05-05
使用UDP協(xié)議實(shí)現(xiàn)單詞翻譯服務(wù)器
這篇文章主要為大家詳細(xì)介紹了如何使用UDP協(xié)議實(shí)現(xiàn)英文單詞翻譯服務(wù)器,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價(jià)值,感興趣的小伙伴可以了解下2023-08-08
C++數(shù)據(jù)結(jié)構(gòu)哈希表詳解
C++標(biāo)準(zhǔn)庫中使用的unordered_map底層實(shí)現(xiàn)是哈希表,下面這篇文章主要給大家介紹了關(guān)于C++中使用哈希表(unordered_map)的一些常用操作方法,需要的朋友可以參考下2022-07-07
C++入門概覽和嘗試創(chuàng)建第一個(gè)C++程序
這篇文章主要介紹了C++入門概覽和嘗試創(chuàng)建第一個(gè)C++程序,同時(shí)也包括編寫類的示例展示C++面向?qū)ο蟮奶匦?需要的朋友可以參考下2015-09-09
基于C語言實(shí)現(xiàn)的貪吃蛇游戲完整實(shí)例代碼
這篇文章主要介紹了基于C語言實(shí)現(xiàn)的貪吃蛇游戲完整實(shí)例代碼,對(duì)于學(xué)習(xí)游戲開發(fā)的朋友有一定的借鑒價(jià)值,需要的朋友可以參考下2014-08-08

