由于c语言中,没有直接的字典,字符串数组等数据结构,所以要借助结构体定义,处理json。如果有对应的数据结构就方便一些, 如python中用json.loads(json)就把json字符串转变为内建的数据结构处理起来比较方便。

一个重要概念:

在cjson中,json对象可以是json,可以是字符串,可以是数字。。。

cjson数据结构定义:

#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6typedef struct cJSON {struct cJSON *next,*prev;    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */int type;                    /* The type of the item, as above. cjson结构的类型上面宏定义的7中之一*/char *valuestring;            /* The item's string, if type==cJSON_String */int valueint;                /* The item's number, if type==cJSON_Number */double valuedouble;            /* The item's number, if type==cJSON_Number */char *string;                /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;
#define cJSON_False 0
#define cJSON_True 1
#define cJSON_NULL 2
#define cJSON_Number 3
#define cJSON_String 4
#define cJSON_Array 5
#define cJSON_Object 6typedef struct cJSON {struct cJSON *next,*prev;    /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */struct cJSON *child;        /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */int type;                    /* The type of the item, as above. cjson结构的类型上面宏定义的7中之一*/char *valuestring;            /* The item's string, if type==cJSON_String */int valueint;                /* The item's number, if type==cJSON_Number */double valuedouble;            /* The item's number, if type==cJSON_Number */char *string;                /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON;

一、解析json 用到的函数,在cJSON.h中都能找到:

/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */
extern cJSON *cJSON_Parse(const char *value);//从 给定的json字符串中得到cjson对象
/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */
extern char  *cJSON_Print(cJSON *item);//从cjson对象中获取有格式的json对象
/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char  *cJSON_PrintUnformatted(cJSON *item);//从cjson对象中获取无格式的json对象/* Delete a cJSON entity and all subentities. */
extern void   cJSON_Delete(cJSON *c);//删除cjson对象,释放链表占用的内存空间/* Returns the number of items in an array (or object). */
extern int    cJSON_GetArraySize(cJSON *array);//获取cjson对象数组成员的个数
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern cJSON *cJSON_GetArrayItem(cJSON *array,int item);//根据下标获取cjosn对象数组中的对象
/* Get item "string" from object. Case insensitive. */
extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string);//根据键获取对应的值(cjson对象)/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
extern const char *cJSON_GetErrorPtr(void);//获取错误字符串

要解析的json

{"semantic": {"slots":    {"name": "张三"}},"rc":   0,"operation":    "CALL","service":  "telephone","text": "打电话给张三"
}
#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h"void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{for(int i=0; i<cJSON_GetArraySize(root); i++)   //遍历最外层json键值对{cJSON * item = cJSON_GetArrayItem(root, i);        if(cJSON_Object == item->type)      //如果对应键的值仍为cJSON_Object就递归调用printJsonprintJson(item);else                                //值不为json对象就直接打印出键和值{printf("%s->", item->string);printf("%s\n", cJSON_Print(item));}}
}int main()
{char * jsonStr = "{\"semantic\":{\"slots\":{\"name\":\"张三\"}}, \"rc\":0, \"operation\":\"CALL\", \"service\":\"telephone\", \"text\":\"打电话给张三\"}";cJSON * root = NULL;cJSON * item = NULL;//cjson对象root = cJSON_Parse(jsonStr);     if (!root) {printf("Error before: [%s]\n",cJSON_GetErrorPtr());}else{printf("%s\n", "有格式的方式打印Json:");           printf("%s\n\n", cJSON_Print(root));printf("%s\n", "无格式方式打印json:");printf("%s\n\n", cJSON_PrintUnformatted(root));printf("%s\n", "一步一步的获取name 键值对:");printf("%s\n", "获取semantic下的cjson对象:");item = cJSON_GetObjectItem(root, "semantic");//printf("%s\n", cJSON_Print(item));printf("%s\n", "获取slots下的cjson对象");item = cJSON_GetObjectItem(item, "slots");printf("%s\n", cJSON_Print(item));printf("%s\n", "获取name下的cjson对象");item = cJSON_GetObjectItem(item, "name");printf("%s\n", cJSON_Print(item));printf("%s:", item->string);   //看一下cjson对象的结构体中这两个成员的意思printf("%s\n", item->valuestring);printf("\n%s\n", "打印json所有最内层键值对:");printJson(root);}return 0;
}

二、构造json:

构造 json比较简单,添加json对象即可。参照例子一看大概就明白了。

主要就是用,cJSON_AddItemToObject函数添加json节点。

xtern cJSON *cJSON_CreateObject(void);
extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item);extern cJSON *cJSON_CreateNull(void);
extern cJSON *cJSON_CreateTrue(void);
extern cJSON *cJSON_CreateFalse(void);
extern cJSON *cJSON_CreateBool(int b);
extern cJSON *cJSON_CreateNumber(double num);
extern cJSON *cJSON_CreateString(const char *string);
extern cJSON *cJSON_CreateArray(void);
extern cJSON *cJSON_CreateObject(void);

例子:     要构建的json:

"semantic": {"slots":    {"name": "张三"}},"rc":   0,"operation":    "CALL","service":  "telephone","text": "打电话给张三"
}
#include <stdio.h>
#include "cJSON.h"int main()
{cJSON * root =  cJSON_CreateObject();cJSON * item =  cJSON_CreateObject();cJSON * next =  cJSON_CreateObject();cJSON_AddItemToObject(root, "rc", cJSON_CreateNumber(0));//根节点下添加cJSON_AddItemToObject(root, "operation", cJSON_CreateString("CALL"));cJSON_AddItemToObject(root, "service", cJSON_CreateString("telephone"));cJSON_AddItemToObject(root, "text", cJSON_CreateString("打电话给张三"));cJSON_AddItemToObject(root, "semantic", item);//root节点下添加semantic节点cJSON_AddItemToObject(item, "slots", next);//semantic节点下添加item节点cJSON_AddItemToObject(next, "name", cJSON_CreateString("张三"));//添加name节点printf("%s\n", cJSON_Print(root));return 0;
}

cJSON 使用详解相关推荐

  1. cJSON库用法详解

    cJSON库用法详解_宁静致远2021的博客-CSDN博客_cjson cJSON库用法详解 问题和需要注意的地方 一.JSON.cJSON简介 1. JSON 简介 2. JSON 语法 3. 开源 ...

  2. Json与CJson详解

            JSON(JavaScript Object Notation,JavaScript对象表示法)是一种由道格拉斯·克罗克福特构想和设计.轻量级的数据交换语言,该语言以易于让人阅读的文字 ...

  3. C语言:JSON格式详解

    C语言:JSON格式详解 C语言:cJSON库用法详解 C语言:使用cJSON库构造JSON C语言:使用cJSON库解析JSON字符串 JSON 简介 JSON全称 JavaScript Objec ...

  4. 性能测试——wrk详解

    前言 上一篇文章我们聊了wrk的安装和使用,这篇文章呢就来和大家说说这个工具怎么进行性能测试或者说wrk的性能测试详解,不说废话了我们直接开始吧. 一.简介 wrk 是一款针对 Http 协议的基准测 ...

  5. Redis详解(1)--原理和机制

    一.性能 1 性能测试 测试环境: RHEL 6.3 / HP Gen8 Server/ 2 * Intel Xeon 2.00GHz(6 core) / 64G DDR3 memory / 300G ...

  6. AliSmartLiving使用详解

    Li Zheng flyskywhy@gmail.com 也可参见我在 github.com 上的博客 AliSmartLiving使用详解.md 阿里云生活物联网平台 安装设备端编译环境 由于 Ub ...

  7. W601温湿度监测与邮件报警系统 — 源码详解(邮件报警模块)

    本项目中的邮件报警模块在用户在网页激活后会自动监测当前的温度,并且与用户设置的温度阈值做比较,一旦检测到当前温度超过用户设定的温度阈值,系统便会向用户所指定的邮箱发送一封报警邮件.当然,你也可以接入各 ...

  8. 从命令行到IDE,版本管理工具Git详解(远程仓库创建+命令行讲解+IDEA集成使用)

    首先,Git已经并不只是GitHub,而是所有基于Git的平台,只要在你的电脑上面下载了Git,你就可以通过Git去管理"基于Git的平台"上的代码,常用的平台有GitHub.Gi ...

  9. JVM年轻代,老年代,永久代详解​​​​​​​

    秉承不重复造轮子的原则,查看印象笔记分享连接↓↓↓↓ 传送门:JVM年轻代,老年代,永久代详解 速读摘要 最近被问到了这个问题,解释的不是很清晰,有一些概念略微模糊,在此进行整理和记录,分享给大家.在 ...

最新文章

  1. 【烦人的问题】有一天发现VSCode中自己的鼠标选择老是跨行选择多段代码,怎么都改不回来,而且用alt+shift+鼠标都无法切换,肿么办?
  2. 通过例子10分钟快速看懂pad_sequence、pack_padded_sequence以及pad_packed_sequence
  3. ubuntu安装mysql可视化工具MySQL-workbench及简单操作
  4. 虚拟机中安装MAC OS X教程(适用所有电脑方法,特别是cpu不支持硬件虚拟化的电脑)...
  5. .Net Core 中的包、元包与框架(Packages, Metapackages and Frameworks)
  6. 线框模型_进行计划之前:线框和模型
  7. yum 多线程插件,apt多线程插件
  8. js+jquery手写弹出提示框
  9. HTML Email 编写指南
  10. CSU 1203 Super-increasing sequence
  11. FormView用法
  12. Spring 计划 7.0
  13. 循环神经网络之LSTM和GRU
  14. 计算机无线网络连接怎么弄,Win7系统如何设置无线网络连接?
  15. 在计算机网络中 将网络的层次结构图,计算机网络基础试卷8
  16. EDI的含义及其重要性
  17. [唯一分解定理]感谢ZLY讲解
  18. 爱思服务器能不能更新苹果手机系统,苹果手机系统升级带来的利和弊,你知道多少?...
  19. 傅里叶变换的简单理解
  20. exlsx表格教程_e某cel表格~的各种基本操作.doc 文档全文预览

热门文章

  1. ICP算法进行点云匹配
  2. Web前端 HTML Day_01
  3. 据说,年薪百万的程序员,都是这么开悟的---笑一笑十年少
  4. php查询更新数据库数据类型,更新Update
  5. Android 渲染机制——SurfaceFlinger
  6. 【java】CGLIB动态代理原理
  7. Rancher2.6全新Monitoring快速入门
  8. 同济大学计算机系拿奖学分绩点,萌新必看NO.8|关于学分绩点奖学金,你想知道的都在这里...
  9. 使用ArcGIS API和Three.js在三维场景中实现动态立体墙效果
  10. SVPWM的一些参数