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

相关文章

Zookeeper安装和配置说明

一、Zookeeper的搭建方式 Zookeeper安装方式有三种,单机模式和集群模式以及伪集群模式。 ■ 单机模式:Zookeeper只运行在一台服务器上,适合测试环境; ■ 伪集群模式:就是在一台物理机上运行多个Zookeeper 实例; ■ 集群模式:Zookeeper运行于一个集群上,适合生产环境,这个计算机集群被称为一个“集合体”(ensemble) Zookeeper通过复制来实现

CentOS7安装配置mysql5.7 tar免安装版

一、CentOS7.4系统自带mariadb # 查看系统自带的Mariadb[root@localhost~]# rpm -qa|grep mariadbmariadb-libs-5.5.44-2.el7.centos.x86_64# 卸载系统自带的Mariadb[root@localhost ~]# rpm -e --nodeps mariadb-libs-5.5.44-2.el7

Centos7安装Mongodb4

1、下载源码包 curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-rhel70-4.2.1.tgz 2、解压 放到 /usr/local/ 目录下 tar -zxvf mongodb-linux-x86_64-rhel70-4.2.1.tgzmv mongodb-linux-x86_64-rhel70-4.2.1/

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

Centos7安装JDK1.8保姆版

工欲善其事,必先利其器。这句话同样适用于学习Java编程。在开始Java的学习旅程之前,我们必须首先配置好适合的开发环境。 通过事先准备好这些工具和配置,我们可以避免在学习过程中遇到因环境问题导致的代码异常或错误。一个稳定、高效的开发环境能够让我们更加专注于代码的学习和编写,提升学习效率,减少不必要的困扰和挫折感。因此,在学习Java之初,投入一些时间和精力来配置好开发环境是非常值得的。这将为我

pdfmake生成pdf的使用

实际项目中有时会有根据填写的表单数据或者其他格式的数据,将数据自动填充到pdf文件中根据固定模板生成pdf文件的需求 文章目录 利用pdfmake生成pdf文件1.下载安装pdfmake第三方包2.封装生成pdf文件的共用配置3.生成pdf文件的文件模板内容4.调用方法生成pdf 利用pdfmake生成pdf文件 1.下载安装pdfmake第三方包 npm i pdfma