cJSON库的安装与使用

2024-06-06 18:58
文章标签 安装 使用 cjson

本文主要是介绍cJSON库的安装与使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原文链接:https://blog.csdn.net/woay2008/article/details/94367652

介绍

cJSON 库是C语言中的最常用的 JSON 库。github 地址是 https://github.com/DaveGamble/cJSON 。

安装

环境是 Ubuntu 16.04。需要先安装cmake。
cJSON 库安装步骤如下:

git clone https://github.com/DaveGamble/cJSON.git
cd cJSON/
mkdir build
cd build/
cmake ..
make
make install

执行完上述命令后,cJSON.h 头文件会安装在 /usr/local/include/cjson 目录下。libcjson.so 库文件会安装在 /usr/local/lib 目录下。还需要将/usr/local/lib目录添加到 /etc/ld.so.conf 文件中,然后执行 /sbin/ldconfig,否则程序在运行时会报 error while loading shared libraries: libcjson.so.1: cannot open shared object file: No such file or directory 错误。
 

Data Structure

cJSON对象结构的数据类型:

/* The cJSON structure: */
typedef struct cJSON
{struct cJSON *next;struct cJSON *prev;struct cJSON *child;int type;char *valuestring;/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */int valueint;double valuedouble;char *string;
} cJSON;

使用

还是使用显示器支持的分辨率的例子来说明如何使用 cJSON 库生成和解析JSON如下的格式:

{"name": "Awesome 4K","resolutions": [{"width": 1280,"height": 720},{"width": 1920,"height": 1080},{"width": 3840,"height": 2160}]
}

使用 cJSON 库时,程序只需包含<cjson/cJSON.h>头文件。而在编译时,需要添加 -lcjson 选项。

 

生成JSON格式

生成 JSON 对象有两种方式:

  • 一是调用 cJSON_CreateXXX 创建相应类型的值(sJSON结构),然后调用 cJSON_AddItemToObject 将值加入到对象中。
  • 二是直接调用 cJSON_AddXXXToObject 创建并添加值到对象中 。

生成 JSON 数组只有一种方式,就是先调用 cJSON_CreateXXX 创建相应类型的值,然后调用 cJSON_AddItemToArray 将值加入到数组中。

最后都要调用 cJSON_Print 将对象或数组转化成 JSON 格式的字符串,调用 cJSON_Delete 释放对象。

生成 JSON 对象的第一种示例代码如下:
 

//NOTE: Returns a heap allocated string, you are required to free it after use.
char* create_monitor(void)
{const unsigned int resolution_numbers[3][2] = {{1280, 720},{1920, 1080},{3840, 2160}};char *string = NULL;cJSON *name = NULL;cJSON *resolutions = NULL;cJSON *resolution = NULL;cJSON *width = NULL;cJSON *height = NULL;size_t index = 0;/* 创建一个对象 */cJSON *monitor = cJSON_CreateObject();if (monitor == NULL){goto end;}/* 创建一个字符串 */name = cJSON_CreateString("Awesome 4K");if (name == NULL){goto end;}/* 将字符串添加到对象中 *//* after creation was successful, immediately add it to the monitor,* thereby transfering ownership of the pointer to it */cJSON_AddItemToObject(monitor, "name", name);/* 创建一个数组 */resolutions = cJSON_CreateArray();if (resolutions == NULL){goto end;}/* 将数组添加到对象中 */cJSON_AddItemToObject(monitor, "resolutions", resolutions);for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index){resolution = cJSON_CreateObject();if (resolution == NULL){goto end;}/* 将对象添加到数组中 */cJSON_AddItemToArray(resolutions, resolution);/* 创建一个数字 */width = cJSON_CreateNumber(resolution_numbers[index][0]);if (width == NULL){goto end;}/* 将数字添加到对象中 */cJSON_AddItemToObject(resolution, "width", width);height = cJSON_CreateNumber(resolution_numbers[index][1]);if (height == NULL){goto end;}cJSON_AddItemToObject(resolution, "height", height);}/* 转换成 JSON 格式的字符串 */string = cJSON_Print(monitor);if (string == NULL){fprintf(stderr, "Failed to print monitor.\n");}end:/* 释放对象 */cJSON_Delete(monitor);return string;
}

生成 JSON 对象的第二种示例代码如下:

//NOTE: Returns a heap allocated string, you are required to free it after use.
char *create_monitor_with_helpers(void)
{const unsigned int resolution_numbers[3][2] = {{1280, 720},{1920, 1080},{3840, 2160}};char *string = NULL;cJSON *resolutions = NULL;size_t index = 0;cJSON *monitor = cJSON_CreateObject();/* 将字符串添加到对象中 */if (cJSON_AddStringToObject(monitor, "name", "Awesome 4K") == NULL){goto end;}/* 将数组添加到对象中,返回一个数组 */resolutions = cJSON_AddArrayToObject(monitor, "resolutions");if (resolutions == NULL){goto end;}for (index = 0; index < (sizeof(resolution_numbers) / (2 * sizeof(int))); ++index){cJSON *resolution = cJSON_CreateObject();/* 将数字添加到对象中 */if (cJSON_AddNumberToObject(resolution, "width", resolution_numbers[index][0]) == NULL){goto end;}if(cJSON_AddNumberToObject(resolution, "height", resolution_numbers[index][1]) == NULL){goto end;}cJSON_AddItemToArray(resolutions, resolution);}string = cJSON_Print(monitor);if (string == NULL) {fprintf(stderr, "Failed to print monitor.\n");}end:cJSON_Delete(monitor);return string;
}

解析JSON格式

解析 JSON 格式,首先要调用 cJSON_Parse 生成用于解析的 cJSON 结构,然后调用 cJSON_GetObjectItemCaseSensitivecJSON_GetObjectItem 获取对应名字的值,用 cJSON_IsXXX 判断值的类型是否正确,然后用 结构中的 valuestringvaluedouble 等成员获取值。实例函数代码如下,这个函数判断显示器是否支持 1920x1080 分辨率:

/* return 1 if the monitor supports full hd, 0 otherwise */
int supports_full_hd(const char *const monitor)
{const cJSON *resolution = NULL;const cJSON *resolutions = NULL;const cJSON *name = NULL;int status = 0;/* 创建一个用于解析的 cJSON 结构 */cJSON *monitor_json = cJSON_Parse(monitor);if (monitor_json == NULL){const char *error_ptr = cJSON_GetErrorPtr();if (error_ptr != NULL){fprintf(stderr, "Error before: %s\n", error_ptr);}status = 0;goto end;}/* 获取名为“name”的值 */name = cJSON_GetObjectItemCaseSensitive(monitor_json, "name");if (cJSON_IsString(name) && (name->valuestring != NULL)){printf("Checking monitor \"%s\".\n", name->valuestring);}/* 获取名为“resolutions“的值,它是一个数组 */resolutions = cJSON_GetObjectItemCaseSensitive(monitor_json, "resolutions");/* 遍历数组 */cJSON_ArrayForEach(resolution, resolutions){cJSON *width = cJSON_GetObjectItemCaseSensitive(resolution, "width");cJSON *height = cJSON_GetObjectItemCaseSensitive(resolution, "height");if (!cJSON_IsNumber(width) || !cJSON_IsNumber(height)){status = 0;goto end;}if ((width->valuedouble == 1920) && (height->valuedouble == 1080)){status = 1;goto end;}}end:cJSON_Delete(monitor_json);return status;
}

main函数

代码如下:

int main(int argc, char **argv)
{char *monitor = create_monitor_with_helpers();printf("%s\n", monitor);if (supports_full_hd(monitor)) {printf("It support full HD.\n");} free(monitor);
}

程序运行结果如下:

{"name":	"Awesome 4K","resolutions":	[{"width":	1280,"height":	720}, {"width":	1920,"height":	1080}, {"width":	3840,"height":	2160}]
}
Checking monitor "Awesome 4K".
It support full HD.

 

这篇关于cJSON库的安装与使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1036953

相关文章

Java使用Curator进行ZooKeeper操作的详细教程

《Java使用Curator进行ZooKeeper操作的详细教程》ApacheCurator是一个基于ZooKeeper的Java客户端库,它极大地简化了使用ZooKeeper的开发工作,在分布式系统... 目录1、简述2、核心功能2.1 CuratorFramework2.2 Recipes3、示例实践3

springboot security使用jwt认证方式

《springbootsecurity使用jwt认证方式》:本文主要介绍springbootsecurity使用jwt认证方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录前言代码示例依赖定义mapper定义用户信息的实体beansecurity相关的类提供登录接口测试提供一

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

springboot security快速使用示例详解

《springbootsecurity快速使用示例详解》:本文主要介绍springbootsecurity快速使用示例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝... 目录创www.chinasem.cn建spring boot项目生成脚手架配置依赖接口示例代码项目结构启用s

Python如何使用__slots__实现节省内存和性能优化

《Python如何使用__slots__实现节省内存和性能优化》你有想过,一个小小的__slots__能让你的Python类内存消耗直接减半吗,没错,今天咱们要聊的就是这个让人眼前一亮的技巧,感兴趣的... 目录背景:内存吃得满满的类__slots__:你的内存管理小助手举个大概的例子:看看效果如何?1.

java中使用POI生成Excel并导出过程

《java中使用POI生成Excel并导出过程》:本文主要介绍java中使用POI生成Excel并导出过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录需求说明及实现方式需求完成通用代码版本1版本2结果展示type参数为atype参数为b总结注:本文章中代码均为

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

MySQL Workbench 安装教程(保姆级)

《MySQLWorkbench安装教程(保姆级)》MySQLWorkbench是一款强大的数据库设计和管理工具,本文主要介绍了MySQLWorkbench安装教程,文中通过图文介绍的非常详细,对大... 目录前言:详细步骤:一、检查安装的数据库版本二、在官网下载对应的mysql Workbench版本,要是

使用Java实现通用树形结构构建工具类

《使用Java实现通用树形结构构建工具类》这篇文章主要为大家详细介绍了如何使用Java实现通用树形结构构建工具类,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录完整代码一、设计思想与核心功能二、核心实现原理1. 数据结构准备阶段2. 循环依赖检测算法3. 树形结构构建4. 搜索子

GORM中Model和Table的区别及使用

《GORM中Model和Table的区别及使用》Model和Table是两种与数据库表交互的核心方法,但它们的用途和行为存在著差异,本文主要介绍了GORM中Model和Table的区别及使用,具有一... 目录1. Model 的作用与特点1.1 核心用途1.2 行为特点1.3 示例China编程代码2. Tab