加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

cJSON 使用详解

发布时间:2020-12-16 19:01:20 所属栏目:百科 来源:网络整理
导读:由于c语言中,没有直接的字典,字符串数组等数据结构,所以要借助结构体定义,处理json。如果有对应的数据结构就方便一些, 如python中用json.loads(json)就把json字符串转变为内建的数据结构处理起来比较方便。 cjson库文件下载 : sourceforge地址 下载完

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

cjson库文件下载

sourceforge地址

下载完之后读一下,README。

编译方式

在工程中添加cJSON.c 和cJSON.h 编译即可,不过要添加-lm链接库gcc选项,如:

gcccJSON.cmain.c-omain-lm

添加-lm是因为用到了,数学库有关的函数。

一个重要概念:

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

cjson数据结构定义

#definecJSON_False0
#definecJSON_True1
#definecJSON_NULL2
#definecJSON_Number3
#definecJSON_String4
#definecJSON_Array5
#definecJSON_Object6

typedefstructcJSON{
structcJSON*next,*prev;/*next/prevallowyoutowalkarray/objectchains.Alternatively,useGetArraySize/GetArrayItem/GetObjectItem*/
structcJSON*child;/*Anarrayorobjectitemwillhaveachildpointerpointingtoachainoftheitemsinthearray/object.*/

inttype;/*Thetypeoftheitem,asabove.cjson结构的类型上面宏定义的7中之一*/

char*valuestring;/*Theitem'sstring,iftype==cJSON_String*/
intvalueint;/*Theitem'snumber,iftype==cJSON_Number*/
doublevaluedouble;/*Theitem'snumber,iftype==cJSON_Number*/

char*string;/*Theitem'snamestring,ifthisitemisthechildof,orisinthelistofsubitemsofanobject.*/
}cJSON;

一、解析json

用到的函数,在cJSON.h中都能找到:

/*SupplyablockofJSON,andthisreturnsacJSONobjectyoucaninterrogate.CallcJSON_Deletewhenfinished.*/
externcJSON*cJSON_Parse(constchar*value);//从给定的json字符串中得到cjson对象
/*RenderacJSONentitytotextfortransfer/storage.Freethechar*whenfinished.*/
externchar*cJSON_Print(cJSON*item);//从cjson对象中获取有格式的json对象
/*RenderacJSONentitytotextfortransfer/storagewithoutanyformatting.Freethechar*whenfinished.*/
externchar*cJSON_PrintUnformatted(cJSON*item);//从cjson对象中获取无格式的json对象

/*DeleteacJSONentityandallsubentities.*/
externvoidcJSON_Delete(cJSON*c);//删除cjson对象,释放链表占用的内存空间

/*Returnsthenumberofitemsinanarray(orobject).*/
externintcJSON_GetArraySize(cJSON*array);//获取cjson对象数组成员的个数
/*Retrieveitemnumber"item"fromarray"array".ReturnsNULLifunsuccessful.*/
externcJSON*cJSON_GetArrayItem(cJSON*array,intitem);//根据下标获取cjosn对象数组中的对象
/*Getitem"string"fromobject.Caseinsensitive.*/
externcJSON*cJSON_GetObjectItem(cJSON*object,constchar*string);//根据键获取对应的值(cjson对象)

/*Foranalysingfailedparses.Thisreturnsapointertotheparseerror.You'llprobablyneedtolookafewcharsbacktomakesenSEOfit.DefinedwhencJSON_Parse()returns0.0whencJSON_Parse()succeeds.*/
externconstchar*cJSON_GetErrorPtr(void);//获取错误字符串

要解析的json

{
"semantic":{
"slots":{
"name":"张三"
}
},"rc":0,"operation":"CALL","service":"telephone","text":"打电话给张三"
}


代码:

#include<stdio.h>
#include<stdlib.h>
#include"cJSON.h"

voidprintJson(cJSON*root)//以递归的方式打印json的最内层键值对
{
for(inti=0;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("%sn",cJSON_Print(item));
}
}
}

intmain()
{
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("Errorbefore:[%s]n",cJSON_GetErrorPtr());
}
else
{
printf("%sn","有格式的方式打印Json:");
printf("%snn",cJSON_Print(root));
printf("%sn","无格式方式打印json:");
printf("%snn",cJSON_PrintUnformatted(root));

printf("%sn","一步一步的获取name键值对:");
printf("%sn","获取semantic下的cjson对象:");
item=cJSON_GetObjectItem(root,"semantic");//
printf("%sn",cJSON_Print(item));
printf("%sn","获取slots下的cjson对象");
item=cJSON_GetObjectItem(item,"slots");
printf("%sn","获取name下的cjson对象");
item=cJSON_GetObjectItem(item,"name");
printf("%sn",cJSON_Print(item));

printf("%s:",item->string);//看一下cjson对象的结构体中这两个成员的意思
printf("%sn",item->valuestring);


printf("n%sn","打印json所有最内层键值对:");
printJson(root);
}
return0;
}

二、构造json

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

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

externcJSON*cJSON_CreateObject(void);
externvoidcJSON_AddItemToObject(cJSON*object,constchar*string,cJSON*item);

externcJSON*cJSON_CreateNull(void);
externcJSON*cJSON_CreateTrue(void);
externcJSON*cJSON_CreateFalse(void);
externcJSON*cJSON_CreateBool(intb);
externcJSON*cJSON_CreateNumber(doublenum);
externcJSON*cJSON_CreateString(constchar*string);
externcJSON*cJSON_CreateArray(void);
externcJSON*cJSON_CreateObject(void);

例子:

要构建的json:

{
"semantic":{
"slots":{
"name":"张三"
}
},"text":"打电话给张三"
}

代码:

#include<stdio.h>
#include"cJSON.h"

intmain()
{
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("%sn",cJSON_Print(root));

return0;
}


代码工程链接

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读