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

相关文章

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可

LiteFlow轻量级工作流引擎使用示例详解

《LiteFlow轻量级工作流引擎使用示例详解》:本文主要介绍LiteFlow是一个灵活、简洁且轻量的工作流引擎,适合用于中小型项目和微服务架构中的流程编排,本文给大家介绍LiteFlow轻量级工... 目录1. LiteFlow 主要特点2. 工作流定义方式3. LiteFlow 流程示例4. LiteF

使用Python开发一个现代化屏幕取色器

《使用Python开发一个现代化屏幕取色器》在UI设计、网页开发等场景中,颜色拾取是高频需求,:本文主要介绍如何使用Python开发一个现代化屏幕取色器,有需要的小伙伴可以参考一下... 目录一、项目概述二、核心功能解析2.1 实时颜色追踪2.2 智能颜色显示三、效果展示四、实现步骤详解4.1 环境配置4.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔