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

cjson库文件下载:

sourceforge地址

一个重要概念:

在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 6 typedef 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": ,
"operation": "CALL",
"service": "telephone",
"text": "打电话给张三"
}

代码:

#include <stdio.h>
#include <stdlib.h>
#include "cJSON.h" void printJson(cJSON * root)//以递归的方式打印json的最内层键值对
{
for(int i=; i<cJSON_GetArraySize(root); i++) //遍历最外层json键值对
{
cJSON * item = cJSON_GetArrayItem(root, i);
if(cJSON_Object == item->type) //如果对应键的值仍为cJSON_Object就递归调用printJson
printJson(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 ;
}

二、构造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": ,
"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());//根节点下添加
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 ;
}

cJSON 使用详解的更多相关文章

  1. Linq之旅:Linq入门详解(Linq to Objects)

    示例代码下载:Linq之旅:Linq入门详解(Linq to Objects) 本博文详细介绍 .NET 3.5 中引入的重要功能:Language Integrated Query(LINQ,语言集 ...

  2. 架构设计:远程调用服务架构设计及zookeeper技术详解(下篇)

    一.下篇开头的废话 终于开写下篇了,这也是我写远程调用框架的第三篇文章,前两篇都被博客园作为[编辑推荐]的文章,很兴奋哦,嘿嘿~~~~,本人是个很臭美的人,一定得要截图为证: 今天是2014年的第一天 ...

  3. EntityFramework Core 1.1 Add、Attach、Update、Remove方法如何高效使用详解

    前言 我比较喜欢安静,大概和我喜欢研究和琢磨技术原因相关吧,刚好到了元旦节,这几天可以好好学习下EF Core,同时在项目当中用到EF Core,借此机会给予比较深入的理解,这里我们只讲解和EF 6. ...

  4. Java 字符串格式化详解

    Java 字符串格式化详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 文中如有纰漏,欢迎大家留言指出. 在 Java 的 String 类中,可以使用 format() 方法 ...

  5. Android Notification 详解(一)——基本操作

    Android Notification 详解(一)--基本操作 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Notification 文中如有纰 ...

  6. Android Notification 详解——基本操作

    Android Notification 详解 版权声明:本文为博主原创文章,未经博主允许不得转载. 前几天项目中有用到 Android 通知相关的内容,索性把 Android Notificatio ...

  7. Git初探--笔记整理和Git命令详解

    几个重要的概念 首先先明确几个概念: WorkPlace : 工作区 Index: 暂存区 Repository: 本地仓库/版本库 Remote: 远程仓库 当在Remote(如Github)上面c ...

  8. Drawable实战解析:Android XML shape 标签使用详解(apk瘦身,减少内存好帮手)

    Android XML shape 标签使用详解   一个android开发者肯定懂得使用 xml 定义一个 Drawable,比如定义一个 rect 或者 circle 作为一个 View 的背景. ...

  9. Node.js npm 详解

    一.npm简介 安装npm请阅读我之前的文章Hello Node中npm安装那一部分,不过只介绍了linux平台,如果是其它平台,有前辈写了更加详细的介绍. npm的全称:Node Package M ...

随机推荐

  1. CUBA Studio 8.0 发布,企业级应用开发平台

    CUBA Platform 是一款开源且免费的企业级应用开发框架,已有将近10年的发展历史,由俄罗斯的 Haulmont  公司开发,CUBA Platform 近期将正式登陆中国,将提供中文网站.中 ...

  2. RocketMQ专题2:三种常用生产消费方式(顺序、广播、定时)以及顺序消费源码探究

    顺序.广播.定时任务 前插 ​ 在进行常用的三种消息类型例子展示的时候,我们先来说一说RocketMQ的几个重要概念: PullConsumer与PushConsumer:主要区别在于Pull与Pus ...

  3. C#Redis初识

    前面博客写了nginx负载均衡,大致了解了下nginx,不过这都是2016年的,2017年的计划也列了,重要的是执行,最近在看RabbitMQ和redis,由于今天和小伙伴们一起去聚餐了,回来的比较晚 ...

  4. 并发编程—— FutureTask 源码分析

    1. 前言 当我们在 Java 中使用异步编程的时候,大部分时候,我们都会使用 Future,并且使用线程池的 submit 方法提交一个 Callable 对象.然后调用 Future 的 get ...

  5. c# 调试运行后,debug目录为空

    运行模式切换到debug,debug目录才有.点运行 按钮 边上不是有 release ,点一下,换成debug

  6. WebForm 【复合控件】

    一 复合控件(取值,赋值用法相近)  RadioButtonList      --单选按钮 (一组列表)  <asp:RadioButtonList ID="RadioButtonL ...

  7. JAVA项目工具包集合

    本文包括工具的下载以及配置,持续更新中…… 1 JDK 官网:https://www.oracle.com 下载:https://www.oracle.com/technetwork/java/jav ...

  8. HTML DOM 知识点整理(一)—— Document对象

    一.DOM对象 DOM对象整体包括: HTML DOM Document对象 HTML DOM 元素对象 HTML DOM 属性对象 HTML DOM 事件对象 HTML DOM Console 对象 ...

  9. js-JavaScript常见的创建对象的几种方式

    1.通过Object构造函数或对象字面量创建单个对象 这些方式有明显的缺点:使用同一个接口创建很多对象,会产生大量的重复代码.为了解决这个问题,出现了工厂模式. 2.工厂模式 考虑在ES中无法创建类( ...

  10. ArcGIS基于DEM计算水流方向的方法(D8算法)

    ArcGIS采用D8算法计算水流方向(9.3.1后新增),输入数据应首先完成了洼地填充处理: One of the keys to deriving hydrologic characteristic ...