目录

一、JSON格式

二、cJSON下载

三、cJSON常用函数接口

四、cJSON解析JSON案例

1.一层键值

2.多层键值(两次为例)

3.json数组解析

五、JSON添加数据 (与链表类似)

三层键值


在做的项目需要发JSON格式的消息并解析,因此学习了利用cJSON解析JSON格式,该格式易于人阅读和编写。同时也易于机器解析和生成。

一、JSON格式

语法:键 / 值

1、以 { 开始,以 } 结束,允许嵌套使用

2、每个键和值成对出现,并使用:分隔。如"age"=23

3、键值对之间用 ,分隔

值的多种类型:

字符串:用 " "

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

数字:整数或浮点数都直接表示

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

数组:用[ ]

 {"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文件,使用的时候,只需要将这两个文件复制到工程目录,然后包含头文件cJSON.h即可。即#include "cJSON.h"

如若出现该情况,链接math库即可 

三、cJSON常用函数接口

1.cJSON_Parse

CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value)函数功能:将一个JSON字符串,按照cJSON结构体的结构序列化整个数据包,并在堆中开辟一块内存存储cJSON结构体返回值:成功返回一个指向内存块中的cJSON的指针,失败返回NULL

2.cJSON_Print

CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item)    //按JSON格式打印CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item)    //不按JSON格式打印函数功能:将整条链表中存放的JSON信息输出到一个字符串中,使用时只需用一个字符串指针(char *)接收该函数返回的指针地址即可。返回值:成功返回一个char*指针并指向位于堆中JSON字符串,失败返回NULL

3.cJSON_Delete

CJSON_PUBLIC(void) cJSON_Delete(cJSON *c)函数功能:释放位于堆中cJSON结构体内存返回值:无

4.cJSON_GetObjectItem

(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string)函数功能:根据键值对的名称从链表中取出对应的值,返回该键值对(链表节点)的地址返回值:成功返回一个指向内存块中的cJSON的指针,失败返回NULL

5.cJSON_GetObjectItem(数组相关)


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.创建对象函数接口

/* 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对象到链表

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

8.从现有的cJSON链表中删除一个对象

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));/* 获取相应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结构体内存return 0;
}

结果:

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));/* 获取相应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结构体内存return 0;
}

结果:

3.json数组解析

/**********************************************************************************      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);    //获取数组大小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结构体内存return 0;
}

结果:

五、JSON添加数据 (与链表类似)

三层键值

/**********************************************************************************      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;
}

结果:

利用cJSON解析JSON格式相关推荐

  1. cjson 对象是json数组型结构体_C语言 - cJSON解析特定格式 含有数组array类型的数据...

    在ESP32中使用了cJSON库,发现很好用.最近服务器端的JSON格式越来越多样,还是有些注意点,需要做下笔记记录下来. cJSON *MAC_arry = cJSON_GetObjectItem( ...

  2. QT解析 JSON 格式的数据

    QT解析 JSON 格式的数据 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.JSON 采用完全独立于语言的文本格式,这些特性使 JSON 成为理想的数 ...

  3. openresty cjson解析json数据

    openresty cjson解析json数据 官网:https://github.com/mpx/lua-cjson 文档:https://kyne.com.au/~mark/software/lu ...

  4. python中json模块_Python使用内置json模块解析json格式数据的方法

    本文实例讲述了Python使用内置json模块解析json格式数据的方法.分享给大家供大家参考,具体如下: Python中解析json字符串非常简单,直接用内置的json模块就可以,不需要安装额外的模 ...

  5. javascript解析json格式的字符串,拼接后显示到表格中

    知识点 解析json格式的字符串 拼接的HTML设置到tbody当中 加载json格式的对象 结果演示 html代码 <!DOCTYPE html> <html><hea ...

  6. C#深入解析Json格式内容

    继上一篇<浅谈C#手动解析Json格式内容>我又来分析加入了一些功能让 这个解析类更实用 本章节最会开放我最终制作成功的Anonymous.Json.dll这个解析库 需要的拿走~ 功能继 ...

  7. java解析sql查询字段_sql解析json格式字段 如何获取json中某个字段的值?

    java将json数据解析为sql语句?小编给你倒一杯热水.可你惦记着其他饮料,所以你将它放置一旁.等你想起那杯水时,可惜它已经变得冰冷刺骨. 图片中是json数据,每个数据的开头都有表名称,操作类型 ...

  8. Java-json系列(一):用GSON解析Json格式数据

    GSON是谷歌提供的开源库,用来解析Json格式的数据,非常好用.如果要使用GSON的话,则要先下载gson-2.2.4.jar这个文件,如果是在Android项目中使用,则在Android项目的li ...

  9. php使用 js格式解析,JavaScript解析JSON格式数据的方法示例

    本文实例讲述了JavaScript解析JSON格式数据的方法.分享给大家供大家参考,具体如下: 1.使用JavaScript提供的eval()函数function JsonText1() { var ...

最新文章

  1. matlab 罗盘图与羽毛图
  2. 等待ajax,等待Ajax调用(post)完成
  3. phpstorm9 增加对.vue的支持
  4. NGS基础 - 参考基因组和基因注释文件
  5. CentOS 6.3(x86_32)下安装Oracle 10g R2
  6. 6.表单提交,input键盘变搜索,有关自定义属性input操作
  7. anaconda安装——添加镜像源
  8. centos 卸载docker_五分钟安装docker并启动第一个docker容器
  9. (转)招行推出的摩羯智能理财,到底是在做什么?
  10. mysql手动编译安装_手动编译安装Mysql
  11. cocos常用工具-TiledMap
  12. rs232读取智能电表_预付费电表高性价比型号推荐 预付费抄表系统免费安装
  13. 六维空间等IPV6资源上不去的一种解决方法
  14. 视觉惯性里程计 综述 VIO Visual Inertial Odometry msckf ROVIO ssf msf okvis ORB-VINS VINS-Mono gtsam
  15. 罗永浩是个挺能折腾的人
  16. c语言函数声明大全及详解,C语言之函数的声明详解
  17. 消防联动控制系统服务器,火灾自动报警消防联动控制系统报价单V4.4.xls
  18. ElasticSearch--Field的使用
  19. 生物特征识别技术领跑者--墨奇科技 全面亮相2022身份识别技术大会
  20. 【课程汇总】OpenHarmony 成长计划知识赋能第三期系列课程(附链接)

热门文章

  1. osgEarth加载谷歌卫星地图的源码案例
  2. Uipath DataTable Activities功能中文描述
  3. zabbix的使用-部署zabbix客户端
  4. Android Realm数据库多条件查询
  5. 7 张图解 CrashLoopBackOff,如何发现问题并解决它?
  6. 相位噪声理论简记(I)Hajimiri模型
  7. HTML制作年历,年历制作.html
  8. 终端安全管理-让企业管理者对公司数据和员工上网行为可控可视
  9. 《UnityAPI.NavMesh导航网格》(Yanlz+Unity+SteamVR+云技术+5G+AI+VR云游戏+Unity+NavMesh+CalculatePath+立钻哥哥++OK++)
  10. 树莓派蓝牙ble gattlib c语言,树莓派的蓝牙通讯(bluez、gattlib)